Class: LHS::Complex

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

Overview

Complex is the main data structure for includes: Can be for example :place, [:place, :customer],

{ places: [:customer

}, { places: { customer: :contract }}]

and so on

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data


8
9
10
# File 'lib/lhs/complex.rb', line 8

def data
  @data
end

Class Method Details

.reduce(data) ⇒ Object


24
25
26
# File 'lib/lhs/complex.rb', line 24

def self.reduce(data)
  new.reduce!(data).unwrap
end

Instance Method Details

#==(other) ⇒ Object


54
55
56
# File 'lib/lhs/complex.rb', line 54

def ==(other)
  unwrap == other.unwrap
end

#merge!(other) ⇒ Object


28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/lhs/complex.rb', line 28

def merge!(other)
  if data.is_a?(Symbol)
    merge_into_symbol!(other)
  elsif data.is_a?(Array)
    merge_into_array!(other)
  elsif data.is_a?(Hash)
    merge_into_hash!(other)
  elsif unwrap != other.unwrap
    raise ArgumentError, "Cannot merge #{unwrap} with #{other.unwrap}"
  end

  self
end

#reduce!(data) ⇒ Object


10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/lhs/complex.rb', line 10

def reduce!(data)
  if data.is_a?(LHS::Complex)
    @data = data.data
  elsif data.is_a?(Array) && !data.empty?
    @data = data.inject(LHS::Complex.new.reduce!([])) { |acc, datum| acc.merge!(LHS::Complex.new.reduce!(datum)) }.data
  elsif data.is_a?(Hash) && !data.empty?
    @data = data.map { |k, v| [k, LHS::Complex.new.reduce!(v)] }.to_h
  else
    @data = data
  end

  self
end

#unwrapObject


42
43
44
45
46
47
48
49
50
51
52
# File 'lib/lhs/complex.rb', line 42

def unwrap
  if data.is_a?(Array)
    result = data.map(&:unwrap)
    result.empty? ? nil : result
  elsif data.is_a?(Hash)
    result = data.map { |k, v| [k, v.unwrap] }.to_h
    result.empty? ? nil : result
  else
    data
  end
end