public
Created

HashInit

  • Download Gist
hashinit.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.