Skip to content

Instantly share code, notes, and snippets.

@armanm
Created May 17, 2014 06:04
Show Gist options
  • Save armanm/b12168286c90fd4b40ad to your computer and use it in GitHub Desktop.
Save armanm/b12168286c90fd4b40ad to your computer and use it in GitHub Desktop.
# encoding: utf-8
# This helper makes hash keys accessable via simple methods.
# This behaviour allows to treat hash elements as object
# properties that can also be overriden
#
# When set_params_hash is not called, then by default this
# code will look for a params method on the object
#
# class TestingClass
# include ParamsDecorator
# set_params_hash :params
#
# def initialize
# @params = { 'arman' => :yellow, 'danny' => 'green', 'smith' => false }
# end
# end
#
# TestClass.new.arman_param # => :yellow
# TestClass.new.danny_param # => 'green'
# TestClass.new.smith_param # => false
#
# or
#
# class TestingClass
# include ParamsDecorator
# set_params_hash :some_method
#
# def some_method
# @params = { 'arman' => :yellow, 'danny' => 'green' }
# end
# end
#
# TestClass.new.arman_param # => :yellow
# TestClass.new.danny_param # => 'green'
#
# or
#
# TestClass.new.smith_param # => false
# class TestingClass
# include ParamsDecorator
#
# def initialize
# @params = { 'arman' => :yellow }
# end
#
# def arman_param
# 'arman is overriden'
# end
# end
#
# TestClass.new.arman_param # => 'arman is overriden'
module ParamsDecorator
def self.included(base)
base.extend const_get("ClassMethods") if const_defined?("ClassMethods")
end
module ClassMethods
private
def set_params_hash(hash_name)
define_method('__params_hash') do
@__params_hash ||= if respond_to?(hash_name)
send(hash_name)
elsif instance_variable_defined?(:"@#{hash_name}")
instance_variable_get(:"@#{hash_name}")
else
super
end
end
end
end
private
def method_missing(missing_method)
method_name = missing_method.to_s
if method_name.end_with?('_param')
key = method_name[0..(method_name.size - ('_param'.size + 1))]
__params_hash[key] if __params_hash.has_key?(key)
else
super
end
end
def __params_hash
@__params_hash ||= if self.respond_to?(:params)
params
else
Hash.new
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment