Class: Realize::Logical::Switch
- Inherits:
-
Object
- Object
- Realize::Logical::Switch
- Defined in:
- lib/realize/logical/switch.rb,
lib/realize/logical/switch/case.rb
Overview
This type of transformer can be categorized as a “comparator”, meaning its intended desire is not a value resolution or value formatting, but a branching resolution. Specifically, you can define cases where, if the value matches, the transformers for the case would be executed. If no case is matched then the default_transformers will be executed.
Defined Under Namespace
Classes: Case
Instance Attribute Summary collapse
-
#cases ⇒ Object
readonly
Returns the value of attribute cases.
-
#default_transformers ⇒ Object
readonly
Returns the value of attribute default_transformers.
-
#key ⇒ Object
readonly
Returns the value of attribute key.
Instance Method Summary collapse
-
#initialize(key:, cases: [], default_transformers: []) ⇒ Switch
constructor
A new instance of Switch.
- #transform(resolver, value, time, record) ⇒ Object
Constructor Details
#initialize(key:, cases: [], default_transformers: []) ⇒ Switch
Returns a new instance of Switch.
24 25 26 27 28 29 30 31 32 |
# File 'lib/realize/logical/switch.rb', line 24 def initialize(key:, cases: [], default_transformers: []) raise ArgumentError, 'key is required' if key.to_s.empty? @cases = Case.array(cases) @default_transformers = Transformers.array(default_transformers) @key = key freeze end |
Instance Attribute Details
#cases ⇒ Object (readonly)
Returns the value of attribute cases.
22 23 24 |
# File 'lib/realize/logical/switch.rb', line 22 def cases @cases end |
#default_transformers ⇒ Object (readonly)
Returns the value of attribute default_transformers.
22 23 24 |
# File 'lib/realize/logical/switch.rb', line 22 def default_transformers @default_transformers end |
#key ⇒ Object (readonly)
Returns the value of attribute key.
22 23 24 |
# File 'lib/realize/logical/switch.rb', line 22 def key @key end |
Instance Method Details
#transform(resolver, value, time, record) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/realize/logical/switch.rb', line 34 def transform(resolver, value, time, record) resolved_value = resolver.get(record, key) matched_case = cases.find { |c| c.match?(resolved_value) } transformers = matched_case ? matched_case.transformers : default_transformers return value if transformers.empty? transformers.inject(value) do |memo, transformer| transformer.transform(resolver, memo, time, record) end end |