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.



129
130
131
# File 'lib/formeze.rb', line 129

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

Instance Method Details

#error_keyObject



133
134
135
# File 'lib/formeze.rb', line 133

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

#error_messageObject



137
138
139
# File 'lib/formeze.rb', line 137

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

#field_errors?(form) ⇒ Boolean

Returns:

  • (Boolean)


149
150
151
# File 'lib/formeze.rb', line 149

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

#field_value?(form) ⇒ Boolean

Returns:

  • (Boolean)


145
146
147
# File 'lib/formeze.rb', line 145

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

#validate(form) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
# File 'lib/formeze.rb', line 153

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)


141
142
143
# File 'lib/formeze.rb', line 141

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