2010-03-02 52 views
7

是否可以在調用期間更改過程的綁定?在調用期間更改`Proc`綁定

class AllValidator 
    def age_validator 
    Proc.new {|value| self.age > value } 
    end 
end 

class Bar 
    attr_accessor :age 
    def doSomething 
    validator = AllValidator.new.age_validator 
    validator.call(25) # How to pass self as the binding? 
    end 
end 

在上面的代碼中,如何在調用過程中更改proc的綁定? 有沒有辦法像eval函數那樣傳遞綁定?

注意 如果上面的例子是真實的,我會用mixin/inheritence等我使用的代碼來證明我的問題的方案。

回答

12

您可以使用instance_eval

class Bar 
    def do_something 
    validator = AllValidator.new.age_validator 

    # Evaluate validator in the context of self. 
    instance_eval &validator 
    end 
end 

如果你想傳遞(如在下面的評論中提到)的參數,你可以使用instance_exec而不是instance_eval,如果你使用Ruby 1.9和Ruby 1.8.7:

class Bar 
    def do_something 
    validator = AllValidator.new.age_validator 

    # instance_exec is like instance_eval with arguments. 
    instance_exec 5, &validator 
    end 
end 

如果你必須使它使用Ruby 1.8.6及以下工作爲好,最好的辦法是給PROC結合爲Bar方法:

class Bar 
    def do_something 
    self.class.send :define_method, :validate, &AllValidator.new.age_validator 
    self.validate 5 
    end 
end 

另一種方法是實施instance_exec舊的Ruby版本(example here)。它所做的只是在調用它之前定義一個方法,並在完成後定義它。

+0

這是否允許你將參數傳遞給'validator'? – 2010-03-02 06:42:30

+0

'instance_eval'有一個姐姐的方法,可以讓你做到這一點,見上面的更新。 – molf 2010-03-02 07:11:32

+0

+1感謝您的詳細解答。 – 2010-03-02 07:57:13

相關問題