LoginSignup
4
4

More than 5 years have passed since last update.

Rails インスタンスメソッド内部でselfを使うべきか

Posted at

書き方のハナシです。

bbatsov/ruby-style-guideによると、

# bad
def ready?
  if self.last_reviewed_at > self.last_updated_at
    self.worker.update(self.content, self.options)
    self.status = :in_progress
  end
  self.status == :verified
end

# good
def ready?
  if last_reviewed_at > last_updated_at
    worker.update(content, options)
    self.status = :in_progress
  end
  status == :verified
end

必要でない時にはselfは書かないほうが主流のようです。

ですが、

Avoid self where not required. (It is only required when calling a self write accessor.) [link]

とあるように、write_accessorのときは明示的にself書く必要があります。

まぁ考えてみれば、write_accessorのときは、

method_name = some_value
variable_name = some_value

のように、変数定義なのか、メソッド呼び出しなのか区別つかないですモンね。だからself明示する必要ありますね。

とまぁそんなバグがあって、考えたので、ここに記しました。

4
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
4
4