ruby-on-rails – 在调用期间更改`Proc`绑定
发布时间:2020-12-17 04:14:56 所属栏目:百科 来源:网络整理
导读:是否可以在调用时更改过程的绑定? class AllValidator def age_validator Proc.new {|value| self.age value } endendclass Bar attr_accessor :age def doSomething validator = AllValidator.new.age_validator validator.call(25) # How to pass self as
是否可以在调用时更改过程的绑定?
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的绑定? 注意 解决方法
你可以使用
instance_eval :
class Bar def do_something validator = AllValidator.new.age_validator # Evaluate validator in the context of self. instance_eval &validator end end 如果要传递参数(如下面的注释中所述),如果使用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).它所做的只是在调用之前定义一个方法,并在完成后取消定义它. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |