1

I have a model that defines methods based off of the entries in another model's table: eg Article and Type. An article habtm types and vice versa.

I define in Article.rb:

 Type.all.each do |type|
   define_method "#{type.name}?" do
     is?(:"#{type.name}")
   end
 end

This works great! it allows me to ensure that any types in the type db result in the methods associated being created, such as:

 article.type?

However, these methods only run when you load the Article model. This introduces certain caveats: for example, in Rails Console, if I create a new Type, its method article.type_name? won't be defined until I reload! everything.

Additionally, the same problem exists in test/rspec: if I create a certain number of types, their associated methods won't exist yet. And in rspec, I don't know how to reload the User model.

Does anyone know a solution here? Perhaps, is there some way to, on creation of a new Type, to reload the Article model's methods? This sounds unlikely.. Any advice or guidance would be great!

4

1 に答える 1

0

モデルのリロードやAPIの変更を少し避けたほうがいいと思います。ではArticle、より一般的な方法による単一のアクセスポイントに本当に反対していますか?

def type?(type)
  return is? type if type.is_a? String # for when type is the Type name already
  is? type.name                        # for when an instance of Type is passed
end

タイプごとに別々のメソッドを使用するように設定している場合は、おそらくこのようなものがTypeクラスで機能します

after_insert do
  block = eval <<-END.gsub(/^ {6}/, '')
    Proc.new { is? :#{self.name} }
  END

  Article.send(:define_method, "#{self.name}?", block)
end
于 2012-11-22T01:45:58.477 に答える