Skip to content

Instantly share code, notes, and snippets.

@stouset
Created August 9, 2012 15:35
Show Gist options
  • Save stouset/3305205 to your computer and use it in GitHub Desktop.
Save stouset/3305205 to your computer and use it in GitHub Desktop.
def_method_missing
class Foo
# regexp matchers yield the MatchData to the block, so you can modify the method
# body based on the regexp
def_method_missing /bar/ do |match|
-> { match.pre_match }
end
# without a regexp matcher, the name of the method is passed to the block, allowing
# you to decide whether or not to implement the method
def_method_missing do |name|
-> { name } if name.length == 4
-> { "bang!" } if name[-1] == '!'
end
end
foo = Foo.new
# regexp-based method_missing
foo.respond_to?(:bazbar) # => true
foo.bazbar # => "baz"
foo.methods.include? /bazbaz/ # => true
# arbitrary Ruby method_missing
foo.respond_to?(:wat) # => false
foo.respond_to?(:what) # => true
foo.what # => :what
foo.methods.include?(:what) # => true
foo.bang # => :bang # matches four-character method name
foo.bang! # => "bang!" # matches last-character bang
foo.wat! # => :wat! # matches four-character method name first
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment