Permalink
Browse files

First commit.

  • Loading branch information...
0 parents commit e38d34e4e8f62d625a39ff7cfb008981ba783902 @josevalim josevalim committed Apr 3, 2009
@@ -0,0 +1,3 @@
+# Version 0.1
+
+* First release
@@ -0,0 +1,20 @@
+Copyright (c) 2009 José Valim
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
143 README
@@ -0,0 +1,143 @@
+Simple Form
+License: MIT
+Version: 0.1
+
+You can also read this README in pretty html at the GitHub project Wiki page:
+
+ http://wiki.github.com/josevalim/simple_form/
+
+Description
+-----------
+
+Simple Form is a ready to go contact form. Just the following lines are needed
+to have a contact form (including the e-mail):
+
+ class ContactForm < SimpleForm
+ subject "My Contact Form"
+ recipients "your.email@your.domain.com"
+ sender{|c| %{"#{c.name}" <#{c.email}>} }
+
+ attribute :name, :validate => true
+ attribute :email, :validate => /[^@]+@[^\.]+\.[\w\.\-]+/
+ attribute :company_name
+ attribute :telephone
+ attribute :message, :validate => true
+ attribute :nickname, :captcha => true
+ end
+
+Then you start a script/console and type:
+
+ c = ContactForm.new(:name => 'José', :email => 'jose@email.com', :message => 'Cool!')
+ c.deliver
+
+Check your inbox and the e-mail will be there, with the sent fields.
+
+SimpleForm is tested and compatible with Rails 2.2.x and Rails 2.3.x. It also
+supports I18n and error messages, just as an ActiveRecord model does.
+
+Installation
+------------
+
+Install Simple Form is very easy. It is stored in GitHub, so just run the following:
+
+ gem sources -a http://gems.github.com
+ sudo gem install josevalim-simple_form
+
+If you want it as plugin, just do:
+
+ script/plugin install git://github.com/josevalim/simple_form.git
+
+API Overview
+------------
+
+== attributes(*attributes)
+
+Declare your form attributes. All attributes declared here will be appended
+to the e-mail, except the ones :captcha is true.
+
+Options:
+
+* :validate - When true, validates the attributes can't be blank.
+ When a regexp is given, check if the attribute matches is not blank and
+ then if it matches the regexp.
+
+* :captcha - When true, validates the attributes must be blank.
+ This is a simple way to avoid spam and the input should be hidden with CSS.
+
+Examples:
+
+ class ContactForm < SimpleForm
+ attributes :name, :validate => true
+ attributes :email, :validate => /[^@]+@[^\.]+\.[\w\.\-]+/
+ attributes :message
+ attributes :nickname, :captcha => true
+ end
+
+ c = ContactForm.new(:nickname => 'not_blank', :email => 'your@email.com', :name => 'José')
+ c.valid? #=> true
+ c.spam? #=> true (raises an error in development, to remember you to hide it)
+ c.deliver #=> false (just delivers if is not a spam and is valid)
+
+ c = ContactForm.new(:email => 'invalid')
+ c.valid? #=> false
+ c.errors.inspect #=> { :name => :blank, :email => :invalid }
+ c.errors.full_messages #=> [ "Name can't be blank", "Email is invalid" ]
+
+ c = ContactForm.new(:name => 'José', :email => 'your@email.com')
+ # save is an alias to deliver to allow it to work with InheritedResources
+ c.save #=> true
+
+== subject(string=nil, &block)
+
+Declares the subject of the contact email. It can be a string or a proc.
+As a proc, it receives a simple form instance. When not specified, it defaults
+to the class human name.
+
+ subject "My Contact Form"
+ subject {|c| "Contacted by #{c.name}"}
+
+== sender(&block)
+
+Declares contact email sender. It can be a string or a proc.
+As a proc, it receives a simple form instance. By default is:
+
+ sender{ |c| c.email }
+
+This requires that your SimpleForm object have at least an email attribute.
+
+== headers(hash)
+
+Additional headers to your e-mail.
+
+== recipients(string_or_array)
+
+Who will receive the e-mail. Can be a string or array.
+
+I18n
+----
+
+All models, attributes and messages in SimpleForm can be used with localized.
+Below is an I18n example file:
+
+ simple_form:
+ models:
+ contact_form: Formulário de contato
+ attributes:
+ name: Nome
+ email: E-mail
+ company_name: Empresa
+ telephone: Telefone
+ message: Mensagem
+ messages:
+ blank: "não pode ficar em branco"
+ invalid: "não é válido"
+ telephone: "deve haver oito dígitos"
+
+Bugs and Feedback
+-----------------
+
+If you discover any bugs, please send an e-mail to jose.valim@gmail.com
+If you just want to give some positive feedback or drop a line, that's fine too!
+
+Copyright (c) 2009 José Valim
+http://josevalim.blogspot.com/
@@ -0,0 +1,19 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Run tests for InheritedResources.'
+Rake::TestTask.new(:test) do |t|
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for InheritedResources.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'SimpleForm'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('MIT-LICENSE')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
@@ -0,0 +1 @@
+File.join(File.dirname(__FILE__), 'lib', 'simple_form')
@@ -0,0 +1,29 @@
+dir = File.dirname(__FILE__)
+require File.join(dir, 'simple_form', 'base')
+require File.join(dir, 'simple_form', 'dsl')
+require File.join(dir, 'simple_form', 'errors')
+require File.join(dir, 'simple_form', 'notifier')
+
+class SimpleForm
+ extend SimpleForm::DSL
+
+ ACCESSORS = [ :form_attributes, :form_validatable, :form_subject,
+ :form_recipients, :form_sender, :form_captcha, :form_headers ]
+
+ DEFAULT_MESSAGES = { :blank => "can't be blank", :invalid => "is invalid" }
+
+ class_inheritable_reader *ACCESSORS
+ protected *ACCESSORS
+
+ # Configure default values
+ #
+ attribute :captcha => true
+ attribute :validate => true
+
+ headers({})
+ recipients([])
+ sender{|c| c.email }
+ subject{|c| c.class.human_name }
+end
+
+SimpleForm::Notifier.template_root = File.join(dir, '..', 'views')
@@ -0,0 +1,113 @@
+class SimpleForm
+
+ # Initialize assigning the parameters given as hash (just as in ActiveRecord).
+ #
+ def initialize(params={})
+ params.each_pair do |attr, value|
+ self.send(:"#{attr}=", value)
+ end unless params.blank?
+ end
+
+ # In development, raises an error if the captcha field is not blank. This is
+ # is good to remember that the field should be hidden with CSS and shown only
+ # to robots.
+ #
+ # In test and in production, it returns true if aall captcha field are blank,
+ # returns false otherwise.
+ #
+ def spam?
+ form_captcha.each do |field|
+ next if send(field).blank?
+
+ if RAILS_ENV == 'development'
+ raise ScriptError, "The captcha field #{field} was supposed to be blank"
+ else
+ return true
+ end
+ end
+
+ return false
+ end
+
+ def not_spam?
+ !spam?
+ end
+
+ # The form is valid if all elements marked to be validated are not blank
+ # and elements given with a regexp match the regexp.
+ #
+ def valid?
+ return false unless errors.empty?
+
+ form_validatable.each_pair do |field, validation|
+ if send(field).blank?
+ errors.add(field, :blank)
+ next
+ end
+
+ errors.add(field, :invalid) if validation.is_a?(Regexp) && send(field) !~ validation
+ end
+
+ errors.empty?
+ end
+
+ def invalid?
+ !valid?
+ end
+
+ # Always return true so when using form_for, the default method will be post.
+ #
+ def new_record?
+ true
+ end
+
+ # Always return nil so when using form_for, the default method will be post.
+ #
+ def id
+ nil
+ end
+
+ # If is not spam and the form is valid, we send the e-mail and returns true.
+ # Otherwise returns false.
+ #
+ def deliver
+ if self.not_spam? && self.valid?
+ SimpleForm::Notifier.deliver_contact(self)
+ return true
+ else
+ return false
+ end
+ end
+ alias :save :deliver
+
+ # Add a human attribute name interface on top of I18n. If email is received as
+ # attribute, it will look for a translated name on:
+ #
+ # simple_form:
+ # attributes:
+ # email: E-mail
+ #
+ def self.human_attribute_name(attribute, options={})
+ I18n.translate("attributes.#{attribute}", options.merge(:default => attribute.to_s.humanize, :scope => [:simple_form]))
+ end
+
+ # Add a human name interface on top of I18n. If you have a model named
+ # SimpleForm, it will search for the localized name on:
+ #
+ # simple_form:
+ # models:
+ # contact_form: Contact form
+ #
+ def self.human_name(options={})
+ underscored = self.name.demodulize.underscore
+ I18n.translate("models.#{underscored}", options.merge(:default => underscored.humanize, :scope => [:simple_form]))
+ end
+
+ # Return the errors in this form. The object returned as the same API as the
+ # ActiveRecord one.
+ #
+ def errors
+ @errors ||= SimpleForm::Errors.new(self)
+ end
+
+end
Oops, something went wrong.

0 comments on commit e38d34e

Please sign in to comment.