Class: Gourami::Form

Inherits:
Object
  • Object
show all
Includes:
Attributes, Coercer, Validations
Defined in:
lib/gourami/form.rb

Overview

Base Form for doing actions based on the attributes specified. This class has to be inherited by different forms, each performing a different action. If needed, #validate method can be overridden if necessary.

Examples:


class LogIn < Gourami::Form

  attribute(:username, :type => :string)
  attribute(:password, :type => :string)

  def validate
    unless valid_login?
      append_error(:username, :invalid_credentials)
    end
  end

  def perform
    User.create(attributes)
  end

  private

  def valid_login?
    user = User.first(:username => username)
    user && check_password_secure(user.password, password)
  end

end

class UpdateUser < Gourami::Form

  VALID_TYPES = %w[buyer seller]

  record(:user, :skip => true)
  attribute(:username, :type => :string)
  attribute(:first_name, :type => :string)
  attribute(:percentage, :type => :integer)
  attribute(:type, :type => :string)

  def validate
    validate_presence(:username)
    validate_length(:username, :min => 2, :max => 64)

    validate_presence(:first_name)

    validate_presence(:percantage)
    validate_range(:percentage, :min => 0, :max => 100)

    validate_presence(:type)
    validate_inclusion(:type, VALID_TYPES)
  end

  def perform
    user.update(attributes)
  end

end

# Usage of the new form class:

form = UpdateUser.new({
  :user => User.first,
  :username => "WeijieWorld",
  :first_name => "Weijie",
  :percentage => "100",
  :type => "buyer"
})

if form.valid?
  form.perform
  # Do something else
else
  # Do something else
end

Constant Summary

Constants included from FormattingConstants

Gourami::FormattingConstants::EMAIL_FORMAT, Gourami::FormattingConstants::HEX_COLOR_FORMAT, Gourami::FormattingConstants::ISRC_FORMAT

Method Summary

Methods included from Coercer

#coerce_array, #coerce_boolean, #coerce_date, #coerce_file, #coerce_float, #coerce_hash, #coerce_integer, #coerce_phone, #coerce_string, #coerce_time, #setter_filter

Methods included from Validations

#any_errors?, #append_error, #attribute_has_errors?, #clear_and_set_errors, #errors, #handle_validation_error, #perform!, #raise_validate_errors, #valid?, #validate, #validate_any, #validate_color_format, #validate_email_format, #validate_filetype, #validate_format, #validate_inclusion, #validate_inclusion_of_each, #validate_isrc_format, #validate_length, #validate_presence, #validate_range, #validate_uniqueness

Methods included from Attributes

#all_attributes, #attribute_provided?, #attributes, #attributes_hash_from_attributes_options, included, #initialize, #provided_attributes, #provided_attributes_names, #set_attributes, #setter_filter