Skip to content

Instantly share code, notes, and snippets.

@gunn
Created February 12, 2011 21:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunn/824163 to your computer and use it in GitHub Desktop.
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.
# 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
# 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