Class: Stark::Struct

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields = {}) ⇒ Struct

Returns a new instance of Struct.



3
4
5
6
7
# File 'lib/stark/struct.rb', line 3

def initialize(fields={})
  fields.each do |k,v|
    send(:"#{k}=", v) if respond_to?(:"#{k}=")
  end
end

Class Method Details

.attr_accessor(*attrs) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/stark/struct.rb', line 46

def self.attr_accessor(*attrs)
  attrs.each do |a|
    n = field_number
    fields[n] = a
    self.field_number n + 1
  end
  super
end

.field_number(n = nil) ⇒ Object



55
56
57
58
# File 'lib/stark/struct.rb', line 55

def self.field_number(n = nil)
  @field_number = n if n
  @field_number ||= 1
end

.fieldsObject



42
43
44
# File 'lib/stark/struct.rb', line 42

def self.fields
  @fields ||= {}
end

Instance Method Details

#[](*args) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/stark/struct.rb', line 9

def [](*args)
  values = []
  args.each do |a|
    case a
    when Fixnum
      n = self.class.fields[a]
      values << (n ? send(n) : nil)
    when Range
      values += self[*a.to_a]
    when String, Symbol
      values << send(a)
    end
  end
  values = values.first if values.size == 1
  values
end

#to_hashObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/stark/struct.rb', line 26

def to_hash
  {}.tap do |hash|
    self.class.fields.each do |idx,name|
      v = send name
      case v
      when Array
        hash[name] = v.map {|e| e.respond_to?(:to_hash) ? e.to_hash : e}
      when Struct
        hash[name] = v.to_hash
      else
        hash[name] = v if v
      end
    end
  end
end