Class: Formeze::Validation

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

Instance Method Summary collapse

Constructor Details

#initialize(field, options, &block) ⇒ Validation

Returns a new instance of Validation.



151
152
153
# File 'lib/formeze.rb', line 151

def initialize(field, options, &block)
  @field, @options, @block = field, options, block
end

Instance Method Details

#error_keyObject



155
156
157
# File 'lib/formeze.rb', line 155

def error_key
  @options.fetch(:error) { :invalid }
end

#error_messageObject



159
160
161
# File 'lib/formeze.rb', line 159

def error_message
  Formeze.translate(error_key, :scope => [:formeze, :errors], :default => 'is invalid')
end

#field_errors?(form) ⇒ Boolean

Returns:

  • (Boolean)


171
172
173
# File 'lib/formeze.rb', line 171

def field_errors?(form)
  form.errors_on?(@field.name)
end

#field_value?(form) ⇒ Boolean

Returns:

  • (Boolean)


167
168
169
# File 'lib/formeze.rb', line 167

def field_value?(form)
  form.send(@field.name) =~ /\S/
end

#validate(form) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
# File 'lib/formeze.rb', line 175

def validate(form)
  if validates?(form) && field_value?(form) && !field_errors?(form)
    return_value = if @block.arity == 1
      @block.call(form.send(@field.name))
    else
      form.instance_eval(&@block)
    end

    form.add_error(@field, error_message) unless return_value
  end
end

#validates?(form) ⇒ Boolean

Returns:

  • (Boolean)


163
164
165
# File 'lib/formeze.rb', line 163

def validates?(form)
  @options.has_key?(:when) ? form.instance_eval(&@options[:when]) : true
end