Skip to content

Instantly share code, notes, and snippets.

@eric1234
Last active August 29, 2015 13:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eric1234/9939118 to your computer and use it in GitHub Desktop.
Save eric1234/9939118 to your computer and use it in GitHub Desktop.
Automatically translated snake_case method calls into their CamelCase equal

A module to automatically translate snake_case method calls into CamelCase method calls. For example:

class MyObject
  include Snakeable
  
  def FooBar
    "baz"
  end
end

MyObject.new.FooBar   # => "baz"
MyObject.new.foo_bar  # => "baz"

snake_case is the convention for Ruby. But sometimes a Ruby object is mirroring another system (database columns, API wrapper, etc) that is using camel case. This module allows you to use the ruby convention and have that automatically translated into the mirrored method.

Obviously the usual caviots with magic metaprogramming apply here:

  • If implementing high performance code use the original CamelCase method. Each time you use the snake_case method it has to do a few additionl operations to verify the method should exist and translate into the CamelCase method.
  • If you have other methods in your class that conflict with the magic snake case methods your methods should override the magic methods. But it could get confusing if your methods are inherited as well or are generated from their own magic metaprogramming.
# https://gist.github.com/eric1234/9939118
module Snakeable
# Patch in our automatic snake_case methods
def method_missing method, *args
if is_snake_case?(method) &&
respond_to?(camelized = method.to_s.camelize.to_sym)
send camelized, *args
else
super
end
end
# So the object including this module will respond to
# Object#respond_to? correctly
def respond_to? method, *args
super || (
is_snake_case?(method) &&
super(method.to_s.camelize.to_sym, *args)
)
end
private
# Is the given method using the snake_case format
def is_snake_case? method
method.to_s =~ /^[a-z]+(?:_[a-z]+)*[?=!]?$/
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment