Class: Remap::Rule::Map::Enum

Inherits:
Proxy
  • Object
show all
Defined in:
lib/remap/rule/map/enum.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Proxy

const_missing, #tap

Class Method Details

.call(&block) ⇒ Any

Builds an enumeration using the block as context

Examples:

enum = Remap::Rule::Map::Enum.call do
  from "B", to: "C"
  value "A"
  otherwise "D"
end

enum.get("A") # => "A"
enum.get("B") # => "C"
enum.get("C") # => "C"
enum.get("MISSING") # => "D"

Returns:

  • (Any)


28
29
30
31
32
33
34
# File 'lib/remap/rule/map/enum.rb', line 28

def self.call(&block)
  unless block
    raise ArgumentError, "no block given"
  end

  new.tap { _1.execute(&block) }
end

Instance Method Details

#from(*keys, to:) ⇒ void

This method returns an undefined value.



60
61
62
63
64
65
# File 'lib/remap/rule/map/enum.rb', line 60

def from(*keys, to:)
  keys.each do |key|
    table[key] = to
    table[to] = to
  end
end

#get(key) {|String| ... } ⇒ Any Also known as: call

Translates key into a value using predefined table

Parameters:

  • key (#hash)

Yields:

  • (String)

    If the key is not found & no default value is set

Returns:

  • (Any)


44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/remap/rule/map/enum.rb', line 44

def get(key, &error)
  unless error
    return get(key) { raise Error, _1 }
  end

  table.fetch(key) do
    unless default == Undefined
      return default
    end

    error["Enum key [#{key}] not found among [#{table.keys.inspect}]"]
  end
end

#otherwise(value) ⇒ void

This method returns an undefined value.



75
76
77
# File 'lib/remap/rule/map/enum.rb', line 75

def otherwise(value)
  @default = value
end

#tableHash

Returns:

  • (Hash)


8
# File 'lib/remap/rule/map/enum.rb', line 8

option :table, default: -> { {} }

#value(*ids) ⇒ void

This method returns an undefined value.



68
69
70
71
72
# File 'lib/remap/rule/map/enum.rb', line 68

def value(*ids)
  ids.each do |id|
    from(id, to: id)
  end
end