Marcin Raczkowski
11/2/2007 8:25:00 PM
I have no idea if someone hacked something like this already, i tried
searching with google but it's hard to type good keys ... anyway here's
what i wrote for SOAP4R that had LOTS of instance variables that i
already had in hash and wanted eay way to assign them.
this should work for almost every class and should provide nice and easy
way to assigning values to instance variables in hash-like way.
of course it exposes all instance variables so encuspulaction (or
whatever you spell it) goes flying out of window.
module ActAsHash
def [](index)
self.instance_variable_get(("@"+index.to_s).to_sym)
end
def []=(index,value)
self.instance_variable_set(("@"+index.to_s).to_sym, value)
end
def from_hash(hash)
hash.each_pair do |k,v|
self[k]=v
end
end
end
and use it simply like
class A
include ActAsHash
attr_accessor :foo
end
a = A.new
a["foo"] = :bar
a.foo => :bar
a[:foo] => :bar
i hope it's usefull for someone :) mayby it can find place in Facets ;)