Class: Eco::Data::Mapper

Inherits:
Object show all
Defined in:
lib/eco/data/mapper.rb

Instance Method Summary collapse

Constructor Details

#initialize(array_of_arrays = [], internal: :last) ⇒ Mapper

it expects [[v1a, v1b], [v2a, v2b] ...]



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/eco/data/mapper.rb', line 6

def initialize (array_of_arrays = [], internal: :last)
  @internal_order = internal
  @source         = array_of_arrays

  if @source
    # internal should be always last in @source
    @source = @source.map { |a| a.reverse } unless internal == :last

    # first declarations take priority
    @by_external = @source.reverse.to_h
    @by_internal = @source.reverse.map do |pair|
      pair.reverse
    end.to_h
  end
end

Instance Method Details

#+(array_of_arrays) ⇒ Object



39
40
41
# File 'lib/eco/data/mapper.rb', line 39

def +(array_of_arrays)
  self.class.new(array_of_arrays + to_a, internal: @internal_order)
end

#as_json(internal: @internal_order) ⇒ Object



22
23
24
# File 'lib/eco/data/mapper.rb', line 22

def as_json(internal: @internal_order)
  to_a(internal: internal)
end

#external?(value) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
# File 'lib/eco/data/mapper.rb', line 55

def external?(value)
  return true if !@source
  @by_external.key?(value)
end

#include?(value) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
63
# File 'lib/eco/data/mapper.rb', line 60

def include?(value)
  return true if !@source
  internal?(value) || external?(value)
end

#internal?(value) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
53
# File 'lib/eco/data/mapper.rb', line 50

def internal?(value)
  return true if !@source
  @by_internal.key?(value)
end

#list(type = :internal) ⇒ Object



43
44
45
46
47
48
# File 'lib/eco/data/mapper.rb', line 43

def list(type = :internal)
  return [] if !@source
  @source.map do |pair|
    type == :internal ? pair.last : pair.first
  end.uniq
end

#self_mapped?(value) ⇒ Boolean

Whether value maps to itself

Returns:

  • (Boolean)


66
67
68
69
# File 'lib/eco/data/mapper.rb', line 66

def self_mapped?(value)
  return false unless include?(value)
  value == to_internal(value)
end

#to_a(internal: @internal_order) ⇒ Object



33
34
35
36
37
# File 'lib/eco/data/mapper.rb', line 33

def to_a(internal: @internal_order)
  @by_internal.map do |int, ext|
    internal == :last ? [ext, int] : [int, ext]
  end
end

#to_external(value) ⇒ Object



76
77
78
79
# File 'lib/eco/data/mapper.rb', line 76

def to_external(value)
  return value if !@source
  @by_internal[value]
end

#to_internal(value) ⇒ Object



71
72
73
74
# File 'lib/eco/data/mapper.rb', line 71

def to_internal(value)
  return value if !@source
  @by_external[value]
end

#to_json(internal: @internal_order) ⇒ Object



26
27
28
29
30
31
# File 'lib/eco/data/mapper.rb', line 26

def to_json(internal: @internal_order)
  content = as_json(internal: internal).map do |pair|
    "  " + pair.to_json
  end.join(",\n")
  "[\n#{content}\n]"
end