Prefer using self over read attribute

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

Metadata

ID: rails-best-practices/read-attribute

Language: Ruby

Severity: Notice

Category: Best Practices

Description

This rule encourages the use of self instead of read_attribute for reading attributes.

read_attribute is an older method in Rails, which can make your code harder to read and understand, especially for those who are not familiar with older Rails methods. Using self to access the model’s attributes makes the code cleaner and easier to read.

To adhere to this rule, replace instances of read_attribute(:attribute_name) with self[:attribute_name]. This practice not only improves readability but also ensures your code is consistent with the latest Rails conventions.

Non-Compliant Code Examples

class Product < ApplicationRecord
  def price
    read_attribute(:price) + 42
  end
end

Compliant Code Examples

class Product < ApplicationRecord
  def price
    self[:price] + 42
  end
end
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: may/unit-testing