Created
January 11, 2012 14:23
-
-
Save bglusman/1594884 to your computer and use it in GitHub Desktop.
HashInit
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I suggest you take a look at https://github.com/intridea/hashie