Ruby Binding Context

Alex V

I have a class "C". I'd like C to run a method A that takes in a block. I'd then like the block to have the context of the class provided.

C.a do

  b # runs main.b instead of C.b

end

Currently, the method b is running in the context of main. I'd like for it to run in the context of the class C How can this be done?

class C
  class << self
    def a(&block)
      block.bind self # NOPE!
      block.binding = self # NOPE!
      yield # NOPE!
    end
    def b
    end
  end
end

PS. This is the same pattern as Rails routes.

elyalvarado

You need to eval the block in the context of the Class:

class C
  class << self
    def a(&block)
      self.instance_eval(&block)
    end
    def b
      puts "hello"
    end
  end
end

C.a do
  b
end

=> "hello"

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related