Class: SuperStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/sstruct.rb

Class Method Summary collapse

Class Method Details

.new(*args) ⇒ Object



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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/sstruct.rb', line 23

def SuperStruct.new(*args)
  @table = []
  @setsyms = []        # Setter symbols
  klass = Class.new
  if (args.size == 1) && (args[0].is_a? Array)
    args = args[0]
  end
  strs = args.map {|x| x.to_s }
  args.each_with_index do |k,i|
    case
	when (! [String,Symbol].include? k.class)
 raise ArgumentError, "Need a String or Symbol"
      when (strs[i] !~ /[_a-zA-Z][_a-zA-Z0-9]*/)
        raise ArgumentError, "Illegal character"
    end
    k = k.intern if k.is_a? String
    @table << k
    @setsyms << (k.to_s + "=").intern
    klass.instance_eval { attr_accessor k }
  end

  setsyms = @setsyms
  table   = @table
  vals    = @vals
  klass.class_eval do
    attr_reader :singleton
    define_method(:initialize) do |*vals|
      n = vals.size
	m = table.size
	case 
 when n < m
   # raise ArgumentError, "Too few arguments (#{n} for #{m})"
   # Never mind... extra variables will just be nil
 when n > m
   raise ArgumentError, "Too many arguments (#{n} for #{m})"
	end
      setsyms.each_with_index do |var,i|
        self.send(var,vals[i])
      end
    end
    define_method(:pretty_print) do |q|  # pp.rb support
      q.object_group(self) do
        q.seplist(self.members, proc { q.text "," }) do |member|
#         self.members.each do |member|
#           q.text ","  # unless q.first?
          q.breakable
          q.text member.to_s
          q.text '='
          q.group(1) do
            q.breakable ''
            q.pp self[member]
          end
        end
      end
    end
    define_method(:inspect) do
      str = "#<#{self.class}:"
      table.each {|item| str << " #{item}=#{self.send(item)}" }
      str + ">"
    end
    define_method(:[]) do |*index|
      case index.map {|x| x.class }
 when [Fixnum]
          self.send(table[*index])
        when [Fixnum,Fixnum], [Range]
   table[*index].map {|x| self.send(x)}
 when [String]
   self.send(index[0].intern)
 when [Symbol]
   self.send(index[0])
      else
        raise ArgumentError,"Illegal index"
	end
    end
    define_method(:[]=) do |*index|
      value = index[-1]
      index = index[0..-2]
      case index.map {|x| x.class }
 when [Fixnum]
          self.send(table[*index])
        when [Fixnum,Fixnum], [Range]
   setsyms[*index].map {|x| self.send(x,value) }
 when [String]
   self.send(index[0].intern,value)
 when [Symbol]
   self.send(index[0],value)
      else
        raise ArgumentError,"Illegal index"
	end
    end
    define_method(:to_a)    { table.map {|x| eval("@"+x.to_s) } }
    define_method(:to_ary)  { to_a }
    define_method(:members) { table.map {|x| x.to_s } }
    define_method(:to_struct) do
      mems = table
      Struct.new("TEMP",*mems)
      # Struct::TEMP.new(*vals) # Why doesn't this work??
      data = mems.map {|x| self.send(x) }
      Struct::TEMP.new(*data)
    end
    define_method(:to_hash) do
      hash = {}
	table.each do |mem|
        mem = mem.to_s
        hash.update(mem => self.send(mem))
      end
	hash
    end
    define_method(:set) {|h| h.each_pair {|k,v| send(k.to_s+"=",v) } }

    # Class methods...

    @singleton = class << self
      self
    end

    @singleton.instance_eval do
      define_method(:members) do 
 table.map {|x| x.to_s }
	end
      me = self
      define_method(:attr_tester) do |*syms| 
        syms.each {|sym| alias_method(sym.to_s+"?",sym) }
      end
    end

  end
  klass
end

.open(*args) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/sstruct.rb', line 154

def SuperStruct.open(*args)
  klass = SuperStruct.new(*args)
  table = @table
  setsyms = @setsyms
  table = @table
  klass.class_eval do
    define_method(:method_missing) do |meth, *args|
      mname = meth.id2name
      if mname =~ /=$/
        getter = mname.chop
        setter = mname
      elsif mname =~ /\?$/
        raise NoMethodError  # ?-methods are not created automatically
      else
        getter = mname
        setter = mname + "="
      end
      gsym = getter.intern
      ssym = setter.intern
      ivar = "@" + getter
      setsyms << setter
      table << getter
      len = args.length
      if mname == getter
        klass.class_eval do                 # getter
          define_method(getter) do
            instance_variable_get(ivar)
          end
        end
      else
        klass.class_eval do                 # setter
          define_method(setter) do |*args|
            if len != 1
              raise ArgumentError, "Wrong # of arguments (#{len} for 1)", 
                    caller(1)
            end
            instance_variable_set(ivar,args[0])
            instance_variable_get(ivar)
          end
        end
      end
      if mname == setter
        self.send(setter,*args)
      else
        if len == 0
          self.send(getter)
        else
          raise NoMethodError, "Undefined method '#{mname}' for #{self}", 
                caller(1)
        end
      end
    end
  end
  klass
end