Dynamically Generated Object with Accessors

I was working on created a super class for use in importing various unknown data types from hashs, so I started playing around with dynamic instance variable and attr_accessor generation and came up with the following, which I thought I would share.

Enjoy!

class Item
  def initialize item
    raise "expected Hash param" unless item.kind_of? Hash
    item.each do |key,value|
      instance_variable_set(clean_key(key), value)
      define_singleton_method(key.to_s) { instance_variable_get( clean_key(key) ) }
      define_singleton_method("#{key.to_s}=") { |val| instance_variable_set( clean_key(key), val ) }
    end
  end

  protected
  # ensure all keys are clean keys, was more necessary when using
  # using missing method, but keeping it to be safe
  def clean_key key
    "@#{key.to_s.gsub(/^\@/, "").gsub(/=$/, "")}".to_sym
  end
end

As always, there may be better/cleaner ways to do this, but this is mine and it worked rather well in with a small amount of code.

Published on in Ruby