Created
October 25, 2012 23:14
-
-
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.
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
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 |
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
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