Skip to content

Instantly share code, notes, and snippets.

@bglusman
Created January 11, 2012 14:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bglusman/1594884 to your computer and use it in GitHub Desktop.
Save bglusman/1594884 to your computer and use it in GitHub Desktop.
HashInit
module HashInit
#example usage:
# instead of this -
#
# class Message
# attr_reader :content, :sender, :subject
# attr_accessor :event
# def initialize(message)
# @content, @sender, @subject, @event =
# message[:content], message[:sender], message[:subject], message[:event]
# end
# type this -
#
# class Message
# attr_reader :content, :sender, :subject
# attr_accessor :event
# include HashInit
# def initialize(message)
# init_ivars message
# end
def init_ivars(hash)
hash.each do |k,v|
set_ivar_from_hash(k,v)
end
end
# can't really recommend using attr_ methods below, but I included them for good measure :-)
def attr_accessor_init(hash)
hash.each do |k,v|
set_ivar_from_hash(k,v)
add_attr_reader(k)
add_attr_writer(k)
end
end
def attr_reader_init(hash)
hash.each do |k,v|
set_ivar_from_hash(k,v)
add_attr_reader(k)
end
end
def attr_writer_init(hash)
hash.each do |k,v|
set_ivar_from_hash(k,v)
add_attr_writer(k)
end
end
private
def set_ivar_from_hash(key, value)
self.instance_variable_set("@#{key}", value)
end
def add_attr_reader(key)
self.class.send(:define_method, key, proc{self.instance_variable_get("@#{key}")})
end
def add_attr_writer(key)
self.class.send(:define_method, "#{key}=", proc{|v| self.instance_variable_set("@#{key}", v)})
end
end
@artemk
Copy link

artemk commented Jan 13, 2012

I suggest you take a look at https://github.com/intridea/hashie

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