Skip to content

Instantly share code, notes, and snippets.

@adz
Last active January 24, 2017 03:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adz/970e3b1a531a5a8b12246df4a20042b8 to your computer and use it in GitHub Desktop.
Save adz/970e3b1a531a5a8b12246df4a20042b8 to your computer and use it in GitHub Desktop.
# 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"]}
[18] pry(main)> schema.call({kind: 'number', answer: '1', optional: false, position: 1, label: 'whatever', options: ['1']}).hints
=> {}
@adz
Copy link
Author

adz commented Jan 24, 2017

BTW if you can't comment, it might be because 'adblocker' blocks out domains with '/adz' - my github handle 😱

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment