Created
August 3, 2016 23:40
-
-
Save rosskevin/f3ee7f49b3fc3f7498e0e62733f26381 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'i18n' | |
require 'reform/form/dry' | |
module Acme | |
module Validations | |
module DslExtension | |
# | |
# Setup our own macros here (much shorter to use) | |
# | |
# @see dry-rb/dry-validation extending_dsl_spec.rb | |
def required_maybe_unique(name, *predicates, &block) | |
required(name).maybe({unique?: name}, *predicates, &block) | |
end | |
def required_unique(name, *predicates, &block) | |
required(name).value({unique?: name}, *predicates, &block) | |
end | |
def required_maybe_id(name, *predicates, &block) | |
required(name).maybe(:id?, *predicates, &block) | |
end | |
def required_id(name, *predicates, &block) | |
required(name).value(:id?, *predicates, &block) | |
end | |
end | |
class Schema < ::Reform::Form::Dry::Schema # Dry::Validation::Schema | |
configure do |config| | |
config.dsl_extensions = DslExtension | |
config.messages = :i18n | |
# option :model, -> { model } # FIXME: form should be passed in, do we need anything? | |
def included_in_enum?(enum, value) | |
return false if value.nil? | |
if (value.kind_of?(String) || value.kind_of?(Symbol)) | |
value = value.to_s | |
enum.keys.include? value | |
else | |
# int | |
enum.values.include? value | |
end | |
end | |
def id?(value) | |
!value.nil? && value.kind_of?(Integer) && value > 0 | |
end | |
def email?(value) | |
!/[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}/i.match(value).nil? | |
end | |
def phone?(value) | |
Util::Phones.parse(value).valid? | |
end | |
def role?(value) | |
included_in_enum? Membership.roles, value | |
end | |
def money?(value) | |
value.instance_of? Money | |
end | |
def kind_of?(type, value) | |
value.kind_of?(type) | |
end | |
def unique?(args, value) | |
if args.is_a? Symbol | |
attribute = args | |
options = {} | |
else | |
attribute, options = args | |
end | |
ActiveRecordORM.unique?(form.model.class, attribute, value, options) | |
end | |
end | |
# create a new schema instance that extends our base schema | |
# @see https://github.com/dry-rb/dry-validation/blob/master/spec/integration/schema/defining_base_schema_spec.rb | |
def self.new_schema(base_schema = Schema, options={}, &block) | |
# allow skipping of passing base_schema | |
if base_schema.is_a? Hash | |
options = base_schema | |
base_schema = Schema | |
end | |
Dry::Validation.Schema(base_schema, options, &block) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment