Class: Trailblazer::Operation::Contract::Validate

Inherits:
Object
  • Object
show all
Defined in:
lib/trailblazer/operation/validate.rb

Defined Under Namespace

Classes: Extract

Instance Method Summary collapse

Constructor Details

#initialize(name: "default", representer: false, params_path: nil, constant: nil) ⇒ Validate

Returns a new instance of Validate.



41
42
43
# File 'lib/trailblazer/operation/validate.rb', line 41

def initialize(name: "default", representer: false, params_path: nil, constant: nil)
  @name, @representer, @params_path, @constant = name, representer, params_path, constant
end

Instance Method Details

#call(ctx) ⇒ Object

Task: Validates contract ‘:name`.



46
47
48
49
50
51
52
# File 'lib/trailblazer/operation/validate.rb', line 46

def call(ctx, **)
  validate!(
    ctx,
    representer: ctx["representer.#{@name}.class"] ||= @representer, # FIXME: maybe @representer should use DI.
    params_path: @params_path
  )
end

#validate!(options, representer: false, from: :document, params_path: nil) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/trailblazer/operation/validate.rb', line 54

def validate!(options, representer: false, from: :document, params_path: nil)
  path     = :"contract.#{@name}"
  contract = @constant || options[path]

  # this is for 1.1-style compatibility and should be removed once we have Deserializer in place:
  options[:"result.#{path}"] = result =
    if representer
      # use :document as the body and let the representer deserialize to the contract.
      # this will be simplified once we have Deserializer.
      # translates to contract.("{document: bla}") { MyRepresenter.new(contract).from_json .. }
      contract.(options[from]) { |document| representer.new(contract).parse(document) }
    else
      # let Reform handle the deserialization.
      contract.(options[params_path])
    end

  result.success?
end