summaryrefslogtreecommitdiff
path: root/lib/ostruct.rb
blob: f083677d8e923688afab175981719df23e338993 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 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
	@table[k] = v
      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!
      @table[mname] = args[0]
    elsif args.length == 0
      @table[mname]
    else
      raise NameError, "undefined method `#{mname}'", caller(1)
    end
  end
  
  def delete_field(name)
    if name.type == Fixnum
      name = name.id2name
    end
    @table.delete name
  end

  def inspect
    str = "<#{self.type}"
    for k,v in @table
      str += " "
      str += k
      str += "="
      str += v.inspect
    end
    str += ">"
    str
  end
end