Created
September 11, 2011 14:14
-
-
Save chsh/1209638 to your computer and use it in GitHub Desktop.
Create Hash with methods for keys. (currently requires ActiveSupport for symbolize_keys :-)
This file contains 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 HashWithMethod < Hash | |
def self.from(hash) | |
instance = self.new | |
hash.symbolize_keys.each do |key, value| | |
case value | |
when Hash | |
value = self.from(value) | |
when Array | |
value = value.map { |v| from_any(v) } | |
end | |
instance[key] = value | |
instance.send :define_refer_method, key | |
instance.send :define_refer_method, "#{key}?", key if (value.is_a?(TrueClass) || value.is_a?(FalseClass)) | |
end | |
instance | |
end | |
private | |
def self.from_any(object) | |
return object unless object.is_a? Hash | |
self.from object | |
end | |
def define_refer_method(key, refkey = nil) | |
refkey ||= key | |
self.class.send :define_method, key do | |
self[refkey] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
h = HashWithMethod.from({a: '1', b: { c: 'xyz' }, t: false })
h.a => 1
h.b.c => 'xyz'
h.t => false
h.t? => false