Skip to content

Instantly share code, notes, and snippets.

@chsh
Created September 11, 2011 14:14
Show Gist options
  • Save chsh/1209638 to your computer and use it in GitHub Desktop.
Save chsh/1209638 to your computer and use it in GitHub Desktop.
Create Hash with methods for keys. (currently requires ActiveSupport for symbolize_keys :-)
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
@chsh
Copy link
Author

chsh commented Sep 11, 2011

Usage:
h = HashWithMethod.from({a: '1', b: { c: 'xyz' }, t: false })
h.a => 1
h.b.c => 'xyz'
h.t => false
h.t? => false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment