Class: Jet::Type::Coercion
- Inherits:
-
Object
- Object
- Jet::Type::Coercion
- Defined in:
- lib/jet/type/coercion.rb
Instance Method Summary collapse
- #call(input) ⇒ Object
- #check_output(input, output) ⇒ Object
- #coercion_check_failure(output, input, error) ⇒ Object
-
#initialize(&blk) ⇒ Coercion
constructor
A new instance of Coercion.
- #match?(output) ⇒ Boolean
- #transformation_failure(input, *errors) ⇒ Object
- #transformation_failure!(*args) ⇒ Object
Constructor Details
#initialize(&blk) ⇒ Coercion
Returns a new instance of Coercion.
6 7 8 9 10 11 12 13 14 15 |
# File 'lib/jet/type/coercion.rb', line 6 def initialize(&blk) raise ArgumentError, "no block given" unless block_given? @checks = [] @matchers = [] instance_eval(&blk) raise ArgumentError, "no `match` blocks given" if @matchers.empty? @checks = @checks.freeze @matchers.freeze @transformer ||= proc { |input| input } end |
Instance Method Details
#call(input) ⇒ Object
17 18 19 20 21 22 23 |
# File 'lib/jet/type/coercion.rb', line 17 def call(input) return Result.failure(:no_coercion_match, input: input) unless match?(input) catch(:transformation_failure) do check_output(input, instance_exec(input, &@transformer)) end end |
#check_output(input, output) ⇒ Object
25 26 27 28 29 30 |
# File 'lib/jet/type/coercion.rb', line 25 def check_output(input, output) @checks.each do |(check, error)| return coercion_check_failure(output, input, error) unless check.(output, input) end Result.success(output, input: input) end |
#coercion_check_failure(output, input, error) ⇒ Object
32 33 34 |
# File 'lib/jet/type/coercion.rb', line 32 def coercion_check_failure(output, input, error) Result.failure(:coercion_check_failure, errors: error, input: input, output: output) end |
#match?(output) ⇒ Boolean
36 37 38 |
# File 'lib/jet/type/coercion.rb', line 36 def match?(output) @matchers.any? { |blk| blk.(output) } end |
#transformation_failure(input, *errors) ⇒ Object
40 41 42 |
# File 'lib/jet/type/coercion.rb', line 40 def transformation_failure(input, *errors) Result.failure(:transformation_failure, errors: errors, input: input) end |
#transformation_failure!(*args) ⇒ Object
44 45 46 |
# File 'lib/jet/type/coercion.rb', line 44 def transformation_failure!(*args) throw :transformation_failure, transformation_failure(*args) end |