Skip to content

Instantly share code, notes, and snippets.

@igor-alexandrov
Last active March 29, 2017 08:51
Show Gist options
  • Save igor-alexandrov/b7d2038ee2a7a12d9f1efc75646787bb to your computer and use it in GitHub Desktop.
Save igor-alexandrov/b7d2038ee2a7a12d9f1efc75646787bb to your computer and use it in GitHub Desktop.
reform2 custom predicates with dry-validation
class Fund::CreateCallForm < BaseForm
# your properties are here
# ...
validation do
configure do
config.messages_file = 'config/locales/dry-validation/errors.yml'
# don't forget about this option to be able to access your form object from your predicates
option :form
# include your custom predicates
include Lion::Predicates
end
required(:fund).filled
required(:name).filled
required(:type) { filled? & included_in?(TRANSACTION_TYPES['Fund::Call']) }
required(:call_date).filled
# use your predicates
required(:due_date).filled { filled? & after_or_equal_to?(:call_date) }
required(:call_categories).value(min_size?: 1)
end
end
module Lion
module Predicates
def self.included(base)
base.class_eval do
def after?(value, current)
value = form.send(value) if value.is_a?(Symbol)
value = value.call if value.is_a?(Proc)
value.present? && (current > value)
end
def after_or_equal_to?(value, current)
value = form.send(value) if value.is_a?(Symbol)
value = value.call if value.is_a?(Proc)
value.present? && (current >= value)
end
def before?(value, current)
value = form.send(value) if value.is_a?(Symbol)
value = value.call if value.is_a?(Proc)
value.present? && (current < value)
end
def before_or_equal_to?(value, current)
value = form.send(value) if value.is_a?(Symbol)
value = value.call if value.is_a?(Proc)
value.present? && (current <= value)
end
def equal_to?(value, current)
value = form.send(value) if value.is_a?(Symbol)
value = value.call if value.is_a?(Proc)
value.present? && (current === value)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment