LoginSignup
3
4

More than 5 years have passed since last update.

キーワード引数でメソッドを簡潔に実装する

Posted at

1. 概要

Rubyでは、キーワード引数を取ることができる。
さらに、Ruby 2.1より、キーワード引数のデフォルト値を省略することができるようになった。
これにより、メソッドをより簡潔に実装することができる。

2. 例

UserがItemに対してLikeするシステムについて考える。
ここで、current_user@itemに対するlikeを取得するfind_like_by_itemメソッドは以下のように書ける。

※ 簡潔な実装を分かりやすく示すためであり、こじつけな例である

# View
link_to 'Like', like_path(current_user.find_like_by_item(@item)), method: :post, remote: true

# Model
class User < ActiveRecord::Base
    :

  def find_like_by_item(item)
    likes.find_by(item_id: item.id)
  end
end

これは、キーワード引数を用いると以下のように書ける。

# View
link_to 'Like', like_path(current_user.like(item: @item)), method: :post, remote: true

# Model
class User < ActiveRecord::Base
    :

  def like(item:)
    likes.find_by(item_id: item.id)
  end
end

キーワード引数が必須であるため、:itemを渡す必要があることが自明であり、すなわちItemに対するLikeを取得するということが分かりやすくなる。

3. 備考

実装においては、メソッドを見てその振る舞いが分かりやすくなければならない。
なので、簡潔に記述するためのひとつの方法と捉えておくべき。

参考

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4