Skip to content

Instantly share code, notes, and snippets.

@mathieul
Created May 22, 2012 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathieul/2771292 to your computer and use it in GitHub Desktop.
Save mathieul/2771292 to your computer and use it in GitHub Desktop.
Caring Form
# app/forms/lead_form.rb
class LeadForm < CaringForm::Model
protect_from_bots
index_on :form_location
metadata :resource_type, :ancillary => true
metadata :inquiry_key
full_name :name
tel :phone_number
email :email_address
looking_for :inquiry_for, :collection => :looking_for_options
us_zip_code :zip_code
text :notes, :optional => true, :label => "Notes about your situation", :input_html => {:rows => 4, :cols => 30}
submit :primary => true, :label => :submit_text
def attributes_for_lead
lead = attributes(:except => {:ancillary => true})
first, *last = *(lead.delete(:name).split(/\s+/))
lead[:first_name] = first
lead[:last_name] = last.join(' ')
lead
end
private
def looking_for_options
Rails.cache.fetch("looking-custom-#{inquiry_key}") do
SomeModel.select('id, value').where(:type => 'looking-for')
end
end
def submit_text
"Request Information"
end
end
# app/controllers/local_controller.rb
class LocalController < ApplicationController
def show
@lead_form = LeadForm.new(:url => lead_path)
end
def create
@lead_form = LeadForm.new(params)
if @lead_form.valid?
lead = create_lead(@lead_form)
redirect_to thank_you_path(lead)
else
render 'show'
end
end
private
def create_lead(form)
attributes = form.attributes_for_lead
if form.spam?
Lead.create_spammy(attributes)
else
Lead.create(attributes)
end
end
end
-# app/views/local/welcome.html.haml
-# short version:
= caring_form_for @lead_form
-# or the longer version for customization:
- caring_form_for @lead_form do |form|
= form.error_messages
= form.metadata
- form.fields(:id => "#{@lead_form.inquiry_key}-fields") do
= form.field :name, :phone_number, :email_address, :inquiry_for
= form.field(:zip_code) if show_zip_code_field
= form.field :notes
- form.fields do
= form.submit :id => "#{@lead_form.inquiry_key}-lead-submit-basic", :class => 'trackable'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment