2016-10-25 7 views
2

私はRailsの懸念を書き込み、静的メソッドとRubyの動的なラムダ

class Baz < ActiveRecord::Base 
    @base = 'awesome' 
    has_many :comments, ->() { where(have_#{@_base} => true) } 
end 

のようなものを実行する必要がありますが、ラムダはCommentコンテキストで実行されますよ。私はeval "has_many :comments, ->() { where(have_#{@_base} => true) }"でハックしました。

evalなしでこの機能を使用する方法はありますか?

ありがとうございました!

答えて

3

あなたはBasicObject#instance_execでそれを達成することができます(それはあなたがブロックに引数を渡すことができます):

class Baz < ActiveRecord::Base 
    @base = 'awesome' 
    instance_exec(@base) do |arg| 
    has_many :comments, -> { where("have_#{arg}" => true) } 
    end 
end 
関連する問題