1998-01-16 07:19:09 -05:00
|
|
|
# ostruct.rb - Python Style Object
|
|
|
|
# just assign to create field
|
|
|
|
#
|
|
|
|
# s = OpenStruct.new
|
|
|
|
# s.foo = 25
|
|
|
|
# p s.foo
|
|
|
|
# s.bar = 2
|
|
|
|
# p s.bar
|
|
|
|
# p s
|
|
|
|
|
|
|
|
class OpenStruct
|
|
|
|
def initialize(hash=nil)
|
|
|
|
@table = {}
|
|
|
|
if hash
|
|
|
|
for k,v in hash
|
2002-11-18 15:09:46 -05:00
|
|
|
@table[k.to_sym] = v
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def method_missing(mid, *args)
|
|
|
|
mname = mid.id2name
|
|
|
|
len = args.length
|
|
|
|
if mname =~ /=$/
|
|
|
|
if len != 1
|
|
|
|
raise ArgumentError, "wrong # of arguments (#{len} for 1)", caller(1)
|
|
|
|
end
|
|
|
|
mname.chop!
|
2002-11-03 06:04:35 -05:00
|
|
|
@table[mname.intern] = args[0]
|
2002-11-18 15:09:46 -05:00
|
|
|
elsif len == 0
|
2002-11-03 06:04:35 -05:00
|
|
|
@table[mid]
|
1998-01-16 07:19:09 -05:00
|
|
|
else
|
2002-11-15 11:12:43 -05:00
|
|
|
raise NoMethodError, "undefined method `#{mname}' for #{self}", caller(1)
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
|
|
|
end
|
2002-11-03 06:04:35 -05:00
|
|
|
|
1998-01-16 07:19:09 -05:00
|
|
|
def delete_field(name)
|
2002-11-03 06:04:35 -05:00
|
|
|
@table.delete name.to_sym
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def inspect
|
2002-10-02 12:45:35 -04:00
|
|
|
str = "<#{self.class}"
|
1998-01-16 07:19:09 -05:00
|
|
|
for k,v in @table
|
2002-11-18 15:09:46 -05:00
|
|
|
str << " #{k}=#{v.inspect}"
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
2002-11-18 15:09:46 -05:00
|
|
|
str << ">"
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
|
|
|
end
|