Created
August 9, 2012 15:35
-
-
Save stouset/3305205 to your computer and use it in GitHub Desktop.
def_method_missing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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