0

ActiveAttr::Model、ActiveAttr:MassAssignment、および ActiveAttr::AttributeDefaults を含む Rails 5 クラスがあります。

メソッドを使用していくつかの属性を定義し、attributeいくつかのインスタンス メソッドを持っています。定義された属性の操作に問題があります。私の問題は、初期化子内で属性値を設定する方法です。いくつかのコード:

class CompanyPresenter
  include ActiveAttr::Model
  include ActiveAttr::MassAssignment
  include ActiveAttr::AttributeDefaults

  attribute :identifier
  # ...
  attribute :street_address
  attribute :postal_code
  attribute :city
  attribute :country
  # ...
  attribute :logo
  attribute :schema_org_identifier
  attribute :productontology
  attribute :website

def initialize(attributes = nil, options = {})
    super
    fetch_po_field
  end

  def fetch_po_field
    productontology = g_i_f_n('ontology') if identifier
  end

  def uri
    @uri ||= URI.parse(website)
  end
  # ...
end

私が書いたように、メソッドfetch_po_fieldは機能しません。productontology がローカル変数であると考えています (g_i_f_n(...)さらに下に定義されており、機能し、その戻り値は正しいです)。この変数を設定するために私が見つけた唯一の方法は、self.productontology代わりに書き込むことです。また、インスタンス変数@uriは属性として定義されておらず、代わりにこの場所にのみ記述され、外部から見えるようになっています。

おそらく私は、Ruby と Rails の基本を単に忘れてしまったのでしょう。ActiveRecord と ActiveModel でこれを長い間行ってきました。self.productontologyを書く必要がある理由、 using@productontologyが機能しない理由、元のコードを書いた私の前任者が@uri属性宣言スタイルに@ 表記を混ぜた理由を誰か説明できますか? 彼がこのようなことをするのには、何か理由があったに違いないと思います。

また、ドキュメントへのポインタにも満足しています。ActiveAttr クラスのメソッドでのインスタンス変数の操作を示す ActiveAttr のドキュメントを見つけることができませんでした。

ありがとうございました :-)

4

1 に答える 1