0

I've been looking around the web and have found a great deal of information on attempting what I am, however one bit of sugar I'd like to add to my Ruby/Rails mixin, is creating a function that looks for a pattern. I want to create a base function called

is_a_*

where * can be anything. Whatever that * is, needs to be retrievable so I can use it inside the function and act accordingly. Do I have to use method_missing?

4

1 回答 1

4

这就是method_missing为此而设计的,例如,这样的东西应该可以工作:

module MyMixin

  def respond_to?(method, priv=false)
    (method.to_s =~ /^is_a_(\w+)$/) || super
  end

  def method_missing(sym, *args)
    if sym.to_s =~ /^is_a_(\w+)$/
      pattern = $1
      # then just do something with pattern here, e.g.:
      puts pattern
    else
      super
    end
  end

end

然后只需包括MyMixin在您的课程中,例如:

class A
  include MyMixin
end

a = A.new
a.is_a_foo
#=> "foo"

ps你并不严格需要覆盖respond_to?,我只是为了完整起见将它包括在内:

a.respond_to?("is_a_foo")
#=> true
a.respond_to?("is_a_bar")
#=> true
a.respond_to?("is__a_foo")
#=> false
于 2012-12-05T03:00:34.460 回答