Today I Learned

hashrocket A Hashrocket project

Redefine #respond_to_missing with #method_missing

Initial attempt:

class User
  def method_missing(name, *args, &block)
    if "#{name}" =~ /foo/
      'exists'
    else
      super
    end
  end
end
> u = User.new
=> #<User:0x007fdf3b152c60>
> u.foo
=> exists
> u.method(:foo)
=> NameError: undefined method `foo' for class `User'
User.class_eval do
  def respond_to_missing?(name, include_private = false)
    "#{name}" =~ /foo/ || super
  end
end
> u = User.new
=> #<User:0x007ffcda847f90>
> u.method(:foo)
=> #<Method: User#foo>
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.