Skip to content

Instantly share code, notes, and snippets.

@alloy-d
Created October 25, 2012 23:14
Show Gist options
  • Save alloy-d/3956061 to your computer and use it in GitHub Desktop.
Save alloy-d/3956061 to your computer and use it in GitHub Desktop.
Awful Ruby hack for forcing the last argument (generally an options hash) to all of a class's methods to be a HashWithIndifferentAccess.
module OptionsWithIndifferentAccess
module ClassMethods
def method_added(method_name)
unless caller[1].match(/`method_added'/)
define_method("_orig_#{method_name}".intern, instance_method(method_name))
define_method(method_name) do |*args, &block|
if args[-1].is_a? Hash
args[-1] = HashWithIndifferentAccess.new(args[-1])
end
self.send "_orig_#{method_name}", *args, &block
end
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
class TestClass12
include OptionsWithIndifferentAccess
def foo(opts={})
puts "opts is a #{opts.class}"
end
end
# tc12 = TestClass12.new
# tc12.foo(test: true)
# => opts is a ActiveSupport::HashWithIndifferentAccess
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment