Class: Trailblazer::Macro::Contract::Validate

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

Defined Under Namespace

Classes: Extract

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Validate.



52
53
54
# File 'lib/trailblazer/macro/contract/validate.rb', line 52

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

Instance Method Details

#call(ctx) ⇒ Object

Task: Validates contract ‘:name`.



57
58
59
60
61
62
63
# File 'lib/trailblazer/macro/contract/validate.rb', line 57

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

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



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/trailblazer/macro/contract/validate.rb', line 65

def validate!(ctx, representer: false, from: :document, params_path: nil)
  contract = ctx[@contract_path] # grab contract instance from "contract.default" (usually set in {Contract::Build()})

  # this is for 1.1-style compatibility and should be removed once we have Deserializer in place:
  ctx[:"result.#{@contract_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.(ctx[from]) { |document| representer.new(contract).parse(document) }
    else
      # let Reform handle the deserialization.
      contract.(ctx[params_path])
    end

  result.success?
end