class Jet::Type::Coercion
Public Class Methods
new(&blk)
click to toggle source
# 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
Public Instance Methods
call(input)
click to toggle source
# 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)
click to toggle source
# 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)
click to toggle source
# 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)
click to toggle source
# File lib/jet/type/coercion.rb, line 36 def match?(output) @matchers.any? { |blk| blk.(output) } end
transformation_failure(input, *errors)
click to toggle source
# 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)
click to toggle source
# File lib/jet/type/coercion.rb, line 44 def transformation_failure!(*args) throw :transformation_failure, transformation_failure(*args) end
Private Instance Methods
check(error = nil, &blk)
click to toggle source
# File lib/jet/type/coercion.rb, line 50 def check(error = nil, &blk) @checks += [[blk, error]] end
match(&blk)
click to toggle source
# File lib/jet/type/coercion.rb, line 54 def match(&blk) @matchers += [blk] end
transform(&blk)
click to toggle source
# File lib/jet/type/coercion.rb, line 58 def transform(&blk) @transformer = blk end