Class: EncodeM::Composite

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/encode_m/composite.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*components) ⇒ Composite

Returns a new instance of Composite.

Raises:

  • (ArgumentError)


8
9
10
11
12
13
# File 'lib/encode_m/composite.rb', line 8

def initialize(*components)
  raise ArgumentError, "Composite key requires at least one component" if components.empty?
  
  @components = components.map { |c| normalize_component(c) }
  @encoded = encode_composite(@components)
end

Instance Attribute Details

#componentsObject (readonly)

Returns the value of attribute components.



6
7
8
# File 'lib/encode_m/composite.rb', line 6

def components
  @components
end

#encodedObject (readonly)

Returns the value of attribute encoded.



6
7
8
# File 'lib/encode_m/composite.rb', line 6

def encoded
  @encoded
end

Instance Method Details

#<=>(other) ⇒ Object

Comparison operations



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/encode_m/composite.rb', line 47

def <=>(other)
  case other
  when EncodeM::Composite
    @encoded <=> other.encoded
  when EncodeM::Numeric, EncodeM::String
    # Single values sort before composites with same first element
    # This maintains hierarchical ordering
    first_comparison = @components.first <=> other
    first_comparison == 0 ? 1 : first_comparison
  else
    nil
  end
end

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



61
62
63
64
65
66
67
68
69
70
# File 'lib/encode_m/composite.rb', line 61

def ==(other)
  case other
  when EncodeM::Composite
    @components == other.components
  when Array
    to_a == other
  else
    false
  end
end

#[](index) ⇒ Object



36
37
38
# File 'lib/encode_m/composite.rb', line 36

def [](index)
  @components[index]
end

#hashObject



74
75
76
# File 'lib/encode_m/composite.rb', line 74

def hash
  @components.hash
end

#inspectObject



32
33
34
# File 'lib/encode_m/composite.rb', line 32

def inspect
  "EncodeM::Composite(#{to_a.map(&:inspect).join(', ')})"
end

#lengthObject Also known as: size



40
41
42
# File 'lib/encode_m/composite.rb', line 40

def length
  @components.length
end

#to_aObject



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/encode_m/composite.rb', line 15

def to_a
  @components.map do |component|
    case component
    when EncodeM::Numeric
      component.value
    when EncodeM::String
      component.value
    else
      component
    end
  end
end

#to_encodedObject



28
29
30
# File 'lib/encode_m/composite.rb', line 28

def to_encoded
  @encoded
end