Created
February 12, 2011 21:44
-
-
Save gunn/824163 to your computer and use it in GitHub Desktop.
Use method_missing to allow camel-cased methods to be called by equivalent underscored names. Written with macruby in mind. Note that #respond_to? should be updated too.
This file contains hidden or 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
# Faster method, the regex / gsub overhead is invoked only the first time, then an alias is used. I'm not sure that this wouldn't introduce side-effects however. What happens when the original camel-cased method is changed / removed, but it's alias remains inplace? | |
class Object | |
alias orig_method_missing method_missing | |
def method_missing name, *args, &block | |
if name =~ /\A[a-z\d_]+\z/ | |
camel_name = name.gsub(/_(.)/) { $1.upcase } | |
if self.respond_to? camel_name | |
# The 'rescue nil' is because macruby seems to do some odd things with classes sometimes (SBElementArray?): | |
self.class.send :alias_method, name, camel_name rescue nil | |
return self.send camel_name, *args, &block | |
end | |
end | |
orig_method_missing | |
end | |
end |
This file contains hidden or 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
# Naive - method_missing and its regexing / gsubing is invoked every method call. | |
class Object | |
alias orig_method_missing method_missing | |
def method_missing name, *args, &block | |
if name =~ /\A[a-z\d_]+\z/ | |
name = name.gsub(/_(.)/) { $1.upcase } | |
self.send name, *args, &block | |
end | |
orig_method_missing | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment