Object method # and dynamic responders

I have a Ruby object (ActiveRecord object in particular) with a name User. It responds to type methods find_by_id, find_by_auth_tokenetc. However, these are not methods that are defined through defor define_method. Instead, they are dynamic methods that are processed through method_missing.

I would like to get a link to one of these methods using Object#method, for example:

User.method(:find_by_auth_token)

This does not seem to work. The best solution I came up with is:

proc { |token| User.find_by_auth_token(token) }

Is there any other way to use a wrapper method like this? Can't I really use Object#methodfor dynamic methods?

+5
source share
1 answer

- "" - , Object#method(:foo) Method, foo .

, Object#method(:foo) Method Object#respond_to_missing? s.t. true :foo. :

class User
  def respond_to_missing?(method_name, include_private = false)
    method_name.to_s.start_with?('find_by_')
  end
end

m = User.new.method(:find_by_hackish_means)
# => #<Method: User#find_by_hackish_means>

( , , ):

m.call
# => NoMethodError: undefined method `find_by_hackish_means' for #<User:0x123>
+5

All Articles