Skip to content

Instantly share code, notes, and snippets.

@adz
Last active January 24, 2017 03:55

Revisions

  1. adz revised this gist Jan 24, 2017. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion dryhints.rb
    Original file line number Diff line number Diff line change
    @@ -40,4 +40,7 @@ def iso8601?(input)
    "must be one of: {:position=>1, :label=>\"whatever\", :kind=>\"number\", :optional=>false, :options=>[\"1\"], :answer=>nil}"]}

    [15] pry(main)> schema.call({kind: 'number', answer: nil, optional: false, position: 1, label: 'whatever', options: ['1']}).errors
    => {:answer=>["must be filled"]}
    => {:answer=>["must be filled"]}

    [18] pry(main)> schema.call({kind: 'number', answer: '1', optional: false, position: 1, label: 'whatever', options: ['1']}).hints
    => {}
  2. adz renamed this gist Jan 24, 2017. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. adz created this gist Jan 24, 2017.
    43 changes: 43 additions & 0 deletions dry hints
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    # Schema looks like:
    configure do
    def iso8601?(input)
    !(!Date.iso8601(input))
    rescue ArgumentError
    false
    end
    end

    required(:position).filled(:int?)
    required(:label).filled
    required(:kind).filled
    required(:optional).filled.bool?
    required(:options).maybe
    required(:answer).maybe

    rule(answer: [:answer, :kind, :optional, :options]) do |answer, kind, optional, options|
    (optional.false? > answer.filled?) &
    ((answer.filled? & kind.eql?('number')) > answer.number?) &
    ((answer.filled? & kind.eql?('date')) > answer.iso8601?) &
    ((answer.filled? & kind.eql?('options')) > answer.included_in?(options))
    end

    # Debug session
    [12] pry(main)> schema.call({kind: 'number', answer: nil, optional: false, position: 1, label: 'whatever', options: []}).messages
    => {:options=>["must be filled"]}

    [13] pry(main)> schema.call({kind: 'number', answer: nil, optional: false, position: 1, label: 'whatever', options: ['1']}).messages
    => {:answer=>
    ["must be filled",
    "must be a number",
    "must be in the form of 'YYYY-MM-DD'",
    "must be one of: {:position=>1, :label=>\"whatever\", :kind=>\"number\", :optional=>false, :options=>[\"1\"], :answer=>nil}"]}

    # Hints should only include "must be a number"
    [14] pry(main)> schema.call({kind: 'number', answer: nil, optional: false, position: 1, label: 'whatever', options: ['1']}).hints
    => {:answer=>
    ["must be a number",
    "must be in the form of 'YYYY-MM-DD'",
    "must be one of: {:position=>1, :label=>\"whatever\", :kind=>\"number\", :optional=>false, :options=>[\"1\"], :answer=>nil}"]}

    [15] pry(main)> schema.call({kind: 'number', answer: nil, optional: false, position: 1, label: 'whatever', options: ['1']}).errors
    => {:answer=>["must be filled"]}