lib/ostruct.rb
DEFINITIONS
This source file includes following functions.
1 # ostruct.rb - Python Style Object
2 # just assign to create field
3 #
4 # s = OpenStruct.new
5 # s.foo = 25
6 # p s.foo
7 # s.bar = 2
8 # p s.bar
9 # p s
10
11 class OpenStruct
12 def initialize(hash=nil)
13 @table = {}
14 if hash
15 for k,v in hash
16 @table[k] = v
17 end
18 end
19 end
20
21 def method_missing(mid, *args)
22 mname = mid.id2name
23 len = args.length
24 if mname =~ /=$/
25 if len != 1
26 raise ArgumentError, "wrong # of arguments (#{len} for 1)", caller(1)
27 end
28 mname.chop!
29 @table[mname] = args[0]
30 elsif args.length == 0
31 @table[mname]
32 else
33 raise NameError, "undefined method `#{mname}'", caller(1)
34 end
35 end
36
37 def delete_field(name)
38 if name.type == Fixnum
39 name = name.id2name
40 end
41 @table.delete name
42 end
43
44 def inspect
45 str = "<#{self.type}"
46 for k,v in @table
47 str += " "
48 str += k
49 str += "="
50 str += v.inspect
51 end
52 str += ">"
53 str
54 end
55 end