Class: MVCLI::Validatable::Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/mvcli/validatable.rb

Instance Method Summary collapse

Constructor Details

#initialize(field, message, options, predicate) ⇒ Rule



169
170
171
172
# File 'lib/mvcli/validatable.rb', line 169

def initialize(field, message, options, predicate)
  @field, @message, @predicate = field, message, predicate
  @options = options.reverse_merge each: true
end

Instance Method Details

#call(validatable, violations, errors) ⇒ Object



174
175
176
177
178
179
180
181
# File 'lib/mvcli/validatable.rb', line 174

def call(validatable, violations, errors)
  value, error = read validatable
  if error
    errors[@field] << error
  else
    check value, violations
  end
end

#check(object, violations) ⇒ Object



183
184
185
186
187
188
189
190
191
192
# File 'lib/mvcli/validatable.rb', line 183

def check(object, violations)
  if object.is_a?(Enumerable) && @options[:each]
    object.each_with_index do |item, i|
      violations["#{@field}[#{i}]"] << @message unless @predicate.call item
    end
  else
    return if object.nil? && !@options[:nil]
    violations[@field] << @message unless @predicate.call object
  end
end

#read(validatable) ⇒ Object



194
195
196
197
198
# File 'lib/mvcli/validatable.rb', line 194

def read(validatable)
  return validatable.instance_eval(@field.to_s), nil
rescue StandardError => e
  return nil, e
end