public
Created

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.

  • Download Gist
alias_underscore.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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
underscore.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.