Prefer using self over read attribute

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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: rtrieu/product-analytics-ui-changes