Skip to content

@bglusman /hashinit.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

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
Something went wrong with that request. Please try again.