Class: Sparsam::Union

Inherits:
Object
  • Object
show all
Includes:
BaseType
Defined in:
lib/sparsam/union.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from BaseType

included, #serialize, #validate

Constructor Details

#initialize(name = nil, value = nil) ⇒ Union

Returns a new instance of Union.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/sparsam/union.rb', line 8

def initialize(name = nil, value = nil)
  if name
    if name.is_a? Hash
      if name.size > 1
        raise ::Sparsam::UnionException,
          "#{self.class} cannot be instantiated with more than one field!"
      end
      value = name.values.first
      name = name.keys.first
    end
  end

  if name
    accessors = name_to_accessors(name)
    unless accessors
      raise Sparsam::Exception, "Unknown key given to #{self.class}.new: #{name}"
    end

    send(accessors.writer, value)
  end
end

Class Method Details

.field_accessor(klass, field_key, field_info) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/sparsam/union.rb', line 52

def self.field_accessor(klass, field_key, field_info)
  field_name = field_info[:name]
  klass.class_eval(<<-EOF, __FILE__, __LINE__)
    def #{field_name}
      if :'#{field_name}' == @setfield
        instance_variable_get(:'@#{field_name}')
      else
        raise ::Sparsam::UnionException, "#{field_name} is not union's set field"
      end
    end

    def #{field_name}=(value)
      if @setfield
        remove_instance_variable(:"@\#{@setfield}")
      end

      @setfield = :'#{field_name}'
      instance_variable_set(:'@#{field_name}', value)
    end
  EOF
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



30
31
32
33
34
35
# File 'lib/sparsam/union.rb', line 30

def ==(other)
  other.equal?(self) ||
  other.instance_of?(self.class) &&
  @setfield == other.get_set_field &&
  get_value == other.get_value
end

#get_set_fieldObject



42
43
44
# File 'lib/sparsam/union.rb', line 42

def get_set_field
  @setfield
end

#get_valueObject



46
47
48
49
50
# File 'lib/sparsam/union.rb', line 46

def get_value
  if @setfield
    send(name_to_accessors(@setfield).reader)
  end
end

#hashObject



38
39
40
# File 'lib/sparsam/union.rb', line 38

def hash
  [self.class.name, @setfield, get_value].hash
end