1998-01-16 15:19:09 +03: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-03 14:04:35 +03:00
|
|
|
@table[k] = v.to_sym
|
1998-01-16 15:19:09 +03: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 14:04:35 +03:00
|
|
|
@table[mname.intern] = args[0]
|
1998-01-16 15:19:09 +03:00
|
|
|
elsif args.length == 0
|
2002-11-03 14:04:35 +03:00
|
|
|
@table[mid]
|
1998-01-16 15:19:09 +03:00
|
|
|
else
|
2002-11-15 01:46:00 +03:00
|
|
|
raise NoMethodError, "undefined method `#{mname}'", caller(1)
|
1998-01-16 15:19:09 +03:00
|
|
|
end
|
|
|
|
end
|
2002-11-03 14:04:35 +03:00
|
|
|
|
1998-01-16 15:19:09 +03:00
|
|
|
def delete_field(name)
|
2002-11-03 14:04:35 +03:00
|
|
|
@table.delete name.to_sym
|
1998-01-16 15:19:09 +03:00
|
|
|
end
|
|
|
|
|
|
|
|
def inspect
|
2002-10-02 20:45:35 +04:00
|
|
|
str = "<#{self.class}"
|
1998-01-16 15:19:09 +03:00
|
|
|
for k,v in @table
|
|
|
|
str += " "
|
2002-11-15 01:46:00 +03:00
|
|
|
str += k.to_s
|
1998-01-16 15:19:09 +03:00
|
|
|
str += "="
|
|
|
|
str += v.inspect
|
|
|
|
end
|
|
|
|
str += ">"
|
|
|
|
str
|
|
|
|
end
|
|
|
|
end
|