开发者

How can I pull a variable into the scope of a singleton class?

module EventSubscriber
  def method_missing(method_name, *args)
    if method_name[/^subscribe_to_(.*)/]
      class << self
        define_method(method_name) do |*arguments|
            # ....
        end
      end

      send(method_name, *args)
    else
      super
    end
  end
end

E开发者_StackOverflowventSubscriber is a module that gets mixed into classes to subscribe to events. If a method called subscribe_to_* gets called, it gets defined (to avoid method_missing overhead again) and then called. How can I bring that variable into scope?

The problem is inside of the singleton class, method_name does not seem to be accessible. Ruby complains about an "undefined local variable or method".

I know I could do this using self.class.send(:define_method ..), but I'd rather not unless I have to. I prefer this format.


What about using:

module EventSubscriber
  extend self 

  def method_missing(method_name, *args)
    if method_name[/^subscribe_to_(.*)/]
      class << self
        define_method(method_name) do |*arguments|
          # ....
        end
      end

      send(method_name, *args)
    else
      super
    end
  end

  def singleton(obj)
    class << obj; self; end
  end

end


Your current problem is that you are using the class << object syntax for accessing the singleton class and trying to access the method_name variable. Any class statement changes the scope; method_name hence does not exist there if it was not defined there.

I am still unsure of what exactly you are trying to accomplish, but here is my attempt to fix your problem:

module EventSubscriber
  def method_missing(method_name, *args)
    if method_name =~ /^subscribe_to_(.+)/
      class << self
        self
      end.define_method(method_name) do |*arguments|
        # ....
      end
      send method_name, *args
    else
      super
    end
  end
end

Note that I also changed the regular expression to something easier to read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜