Class: Mustermann::Mapper
- Inherits:
-
Object
- Object
- Mustermann::Mapper
- Defined in:
- lib/mustermann/mapper.rb
Overview
A mapper allows mapping one string to another based on pattern parsing and expanding.
Instance Method Summary collapse
-
#[]=(key, value) ⇒ Object
Add a single mapping.
-
#convert(input, values = {}) ⇒ Object
(also: #[])
Convert a string according to mappings.
-
#initialize(map = {}, additional_values: :ignore, **options, &block) ⇒ Mapper
constructor
Creates a new mapper.
-
#to_h ⇒ Hash{Patttern: Expander}
Hash version of the mapper.
-
#update(map) ⇒ Object
Add multiple mappings.
Constructor Details
#initialize(**options) { ... } ⇒ Mapper #initialize(**options) {|mapper| ... } ⇒ Mapper #initialize(map = {}, **options) ⇒ Mapper
Creates a new mapper.
47 48 49 50 51 52 53 |
# File 'lib/mustermann/mapper.rb', line 47 def initialize(map = {}, additional_values: :ignore, **, &block) @map = [] @options = @additional_values = additional_values block.arity == 0 ? update(yield) : yield(self) if block update(map) if map end |
Instance Method Details
#[]=(key, value) ⇒ Object
Add a single mapping.
88 89 90 |
# File 'lib/mustermann/mapper.rb', line 88 def []=(key, value) update key => value end |
#convert(input, values = {}) ⇒ Object Also known as: []
Convert a string according to mappings. You can pass in additional params.
76 77 78 79 80 81 82 |
# File 'lib/mustermann/mapper.rb', line 76 def convert(input, values = {}) @map.inject(input) do |current, (pattern, )| params = pattern.params(current) params &&= Hash[values.merge(params).map { |k,v| [k.to_s, v] }] .(params) ? .(params) : current end end |
#to_h ⇒ Hash{Patttern: Expander}
Returns Hash version of the mapper.
67 68 69 |
# File 'lib/mustermann/mapper.rb', line 67 def to_h Hash[@map] end |
#update(map) ⇒ Object
Add multiple mappings.
58 59 60 61 62 63 64 |
# File 'lib/mustermann/mapper.rb', line 58 def update(map) map.to_h.each_pair do |input, output| input = Mustermann.new(input, **@options) output = Expander.new(*output, additional_values: @additional_values, **@options) unless output.is_a? Expander @map << [input, output] end end |