Last active
August 29, 2015 14:06
-
-
Save dchandekstark/05c453589c301dcbdfb1 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 'forwardable' | |
module Hydra | |
module Validations | |
class EnumerableValidator < ActiveModel::EachValidator | |
extend Forwardable | |
def_delegator :@member_validator, :validate_each, :validate_member | |
def_delegator :@member_validator, :kind | |
def initialize(member_validator, options = {}) | |
unless member_validator.is_a? ActiveModel::EachValidator | |
raise ArgumentError, "Member validator must be an instance of an ActiveModel::EachValidator subclass" | |
end | |
@member_validator = member_validator | |
super(options) | |
end | |
def validate_each(record, attribute, value) | |
return validate_member(record, attribute, value) unless value.respond_to?(:each) | |
if value.respond_to?(:empty?) && value.empty? | |
record.errors.add(attribute, "can't be empty") unless options[:allow_empty] | |
else | |
value.each do |v| | |
previous_error_count = record.errors[attribute].size rescue 0 | |
validate_member(record, attribute, v) | |
messages = record.errors[attribute] | |
if messages && messages.size > previous_error_count | |
record.errors.add(attribute, fixed_message(v, messages.pop)) | |
end | |
end | |
end | |
end | |
protected | |
def fixed_message(value, message) | |
"value \"#{value}\" #{message}" | |
end | |
end | |
end | |
end |
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 'hydra/validations/enumerable_validator' | |
module Hydra | |
module Validations | |
class FormatValidator < EnumerableValidator | |
def initialize(options = {}) | |
member_validator = ActiveModel::Validations::FormatValidator.new(options.dup) | |
super(member_validator, options) | |
end | |
module HelperMethods | |
def validates_format_of *attr_names | |
validates_with FormatValidator, _merge_attributes(attr_names) | |
end | |
end | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment