在哪里把我的ruby类类“元生成器”?

时间:2011-03-21 23:47:55

标签: ruby-on-rails metaprogramming

我有以下内容:

class ThirdParty < ActiveRecord::Base
  # Dynamically adds accessors of the requested kind.
  def self.has_many_children_of_kind (kinds=[])
    puts 'In generator method'
    kinds.each  { |k|
      n            = k.to_s
      self.class_eval  %{
        has_many    :#{n}_as_owner, {
                      :foreign_key  => :owner_id,
                      :class_name    => 'ThirdPartiesLink',
                      :conditions    => #{ k!=:third_parties ? "{ :kind => '"+n.singularize+"' }" : 'nil' }
                    }
        has_many    :#{n}, {
                      :through      => :#{n}_as_owner,
                      :source        => :owned
                    }
        }
      }
  end
  # Make dynamic associations of given kinds.
  has_many_children_of_kind  [ :third_parties, :customers, :suppliers, :contacts ]
end
class ThirdPartiesLink < ActiveRecord::Base
  belongs_to  :owner,  :foreign_key => :owner_id,  :class_name => 'ThirdParty'
  belongs_to  :owned,  :foreign_key => :owned_id,  :class_name => 'ThirdParty'
  # This model has a column named 'kind' for storing the link kind.
end

一切都像我期望的那样完美。 这一行:

has_many_children_of_kind [ :third_parties, :customers, :suppliers, :contacts ]

生成:

has_many :third_parties_as_owner, { :foreign_key => :owner_id, :class_name => 'ThirdPartiesLink', :conditions => nil }
has_many :third_parties, { :through => :third_parties_as_owner, :source => :owned } 
has_many :customers_as_owner, { :foreign_key => :owner_id, :class_name => 'ThirdPartiesLink', :conditions => { :kind => 'customer' } }
has_many :customers, { :through => :customers_as_owner, :source => :owned } 
has_many :suppliers_as_owner, { :foreign_key => :owner_id, :class_name => 'ThirdPartiesLink', :conditions => { :kind => 'supplier' } }
has_many :suppliers, { :through => :suppliers_as_owner, :source => :owned } 
has_many :contacts_as_owner, { :foreign_key => :owner_id, :class_name => 'ThirdPartiesLink', :conditions => { :kind => 'contact' } }
has_many :contacts, { :through => :contacts_as_owner, :source => :owned }

但是,每次刷新使用ThirdParty对象的页面时,“In generator method”行都会在控制台中输出。

我尝试了几件事: 把has_many_children_of_kind放在我的应用程序初始化器中而不是把它放在ThirdParty类中(我真的不喜欢它,它更像是一个测试而不是其他任何东西)。在这种情况下,页面的第一个显示在服务器重新启动后工作,但是如果我刷新页面,则在ThirdParty实例上调用时找不到生成的方法...

在启动服务器的过程中,确保ThirdParty类一次性使用访问器编写的方法是什么?

感谢您的时间! 皮尔。

编辑:生成器方法块也可以是这样的:

kinds.each  { |k|
  n            = k.to_s
 has_many("#{n}_as_owner".to_sym, {
      :foreign_key  => :owner_id,
      :class_name   => 'ThirdPartiesLink',
      :conditions   => ( k!=:third_parties ? { :kind => n.singularize } : nil)
    }
  )
 has_many(n.to_sym, {
      :through      => "#{n}_as_owner".to_sym,
      :source       => :owned
    }
  )
}

什么是最好的?评价还是最新的?我会说最新的,因为没有涉及解析器/ eval,所以它可能会快一点,对吗?

1 个答案:

答案 0 :(得分:0)

一个好的答案是MikeOnRails指出的答案。