Techioz Blog

Railsで「ヘルパー」メソッドを属性/列に追加するにはどうすればよいですか? [閉まっている]

概要

「Items」という名前のテーブル、「name」という名前の列、および「quantity」という名前の列があるとします。

次に、次のような item のインスタンスがあるとします。

@item = Item.first

このインスタンスでは、次のようなメソッドを呼び出すことができます。

@item.name.present?
@item.quantity.is_a?(Integer)

たとえば、次のように呼び出したい場合、独自のメソッドをすべての列に追加するにはどうすればよいでしょうか。

@item.name.custom_method?
@item.quantity.custom_method?
@item.name.custom_method_2(:xyz)
@item.quantity.custom_method_2(:xyz)

そこで、すべての列属性にそれぞれメソッドを追加し、それを使ってカスタム処理を行いたいと思います。私はそれにいくつかの宝石を見てきました、そしてRailsはそれを例えばダーティで行い、変更を追加しますか?列/属性に。

解決策

いわゆる属性メソッドを定義できます。これにより、すべての属性のメソッドが定義されます。

# app/models/model.rb

class Model < ApplicationRecord
  attribute_method_suffix "_is_custom?"

  private

  def attribute_is_custom? attr
    "#{attr} is custom."
  end
end
>> Model.first.name_is_custom?
=> "name is custom."
>> Model.first.id_is_custom?
=> "id is custom."

https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://api.rubyonrails.org/classes/ActiveModel/AttributeMethods.html