ruby - How do I change the context of lambda? -


if run code below error.

class c   def self.filter_clause param_1     puts param_1     yield # context of param class b   end    def hi     "hello"   end end  class b   def self.filter(value, lambda)     code = lambda { filter_clause(value, &lambda) }     c.instance_exec(&code)   end    filter(:name, ->{ hi }) end 

the error

nameerror: undefined local variable or method `hi' b:class (pry):17:in `block in <class:b>' 

from understanding reason lambda running under context of class b. can't find method def hi. can't figure out how run under context of class c.

essentially want able inject method being called in class accepts argument , block.

for example:

filter_clause("value", ->{ hi })

is possible?

not sure if making sense.

you're close. if want lambda(/block, really) execute in context of instance of c (since hi instance method on c), you'll need instantiate , instance_exec block on new instance:

class c   def self.filter_clause param_1, &block     puts new.instance_exec &block   end    def hi     "hello"   end end  class b   def self.filter(value, lambda)     code = lambda { filter_clause(value, &lambda) }     c.instance_exec(&code)   end    filter(:name, ->{ hi }) end  # => hello 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -