Saturday, May 26, 2007

HashToAttributes.rb

# When this class is initialized, it takes in a Hash and uses the key/value
# pairs to create instance variables. The problem here is that each key needs to
# be verified to make sure it conforms to the naming rules.
#
# This is like converting a Hash to an object (a Hash.to_o method, if you will).
# Great for when you're hacking up a script to parse some text/XML/YAML as a
# once-off. I wouldn't recommend this be used in a production environment.
# 
class HashToAttributes
  attr_reader :attr1, :attr2, :attr3
  attr_writer :attr3
  
  def initialize(hash)
    # Each key becomes an instance variable
    # TODO: check that key conforms to naming rules
    hash.each do |key, value|
      instance_variable_set(("@" + key).to_sym, value);
    end
  end
end

hsh = { 'attr1' => "Oh Vey", 'attr2' => "Virtua Cop 2", 'attr3' => true }
obj = HashToAttributes.new(hsh)
puts obj.attr1       # => "Oh Vey"
puts obj.attr2       # => "Virtua Cop 2"
obj.attr3 = false
puts obj.attr3       # => false

No comments: