Skip to content

Instantly share code, notes, and snippets.

@kwando
Created November 30, 2015 09:22
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 kwando/01ff386521d46a432ebe to your computer and use it in GitHub Desktop.
Save kwando/01ff386521d46a432ebe to your computer and use it in GitHub Desktop.
class MailboxInputValidator < Dry::Validation::Schema
key(:per_page) { |pp| pp.int? & pp.gt?(0) & pp.lteq?(100) }
key(:page) { |p| p.int? & p.gt?(0) }
end
class MailboxInput < Dry::Data::Struct
attribute :page, 'coercible.int'
attribute :per_page, 'coercible.int'
def offset
(page - 1) * per_page
end
end
# Functions is a transproc registry
MailboxInputMapper = Functions[:accept_keys, ['page', 'per_page']] >> Functions[:symbolize_keys!]
# in your controller / endpoint
input = {page: 1, per_page: 10}.merge!(MailboxInputMapper[params])
errors = validator.messages(input)
if errors.empty?
# everything is fine
input = MailboxInput.new(input)
mails = mailbox_store.load(limit: input.per_page, offset: input.offset)
else
# render bad request
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment