Skip to content

Instantly share code, notes, and snippets.

@nu7hatch
Created June 20, 2013 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nu7hatch/5824064 to your computer and use it in GitHub Desktop.
Save nu7hatch/5824064 to your computer and use it in GitHub Desktop.
module Hashifiable
def hashify(*args)
hashified = {}
args.each do |arg|
case arg
when Symbol
hashified[arg] = lambda { |obj| obj.send(arg) }
when Hash
arg.each do |key, proc|
hashified[key] = lambda { |obj| obj.instance_exec(&proc) }
end
end
end
## Defines to_hash method dinamically with the key/values specified
## in *args.
define_method :to_h do
hashified.to_a.inject({}) do |result, (key, callable)|
result[key] = callable.call(self)
result
end
end
alias_method :to_hash, :to_h
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment