From cd85f72e21542adc11c6abd189aaf3e79538b3cd Mon Sep 17 00:00:00 2001 From: Dan Croak Date: Tue, 4 Aug 2009 15:48:45 -0400 Subject: [PATCH] added clearance_views generator. by default, creates formtastic views which pass all tests and features. --- .gitignore | 1 + CHANGELOG.textile | 7 + Rakefile | 45 +- .../clearance_features_generator.rb | 6 +- generators/clearance_views/USAGE | 0 .../clearance_views_generator.rb | 27 + .../formtastic/passwords/edit.html.erb | 21 + .../formtastic/passwords/new.html.erb | 15 + .../formtastic/sessions/new.html.erb | 22 + .../formtastic/users/_inputs.html.erb | 6 + .../templates/formtastic/users/new.html.erb | 10 + test/rails_root/config/environment.rb | 3 + .../.specification | 67 + .../justinfrench-formtastic-0.2.1/MIT-LICENSE | 20 + .../README.textile | 383 +++ .../justinfrench-formtastic-0.2.1/Rakefile | 58 + .../formtastic_stylesheets_generator.rb | 21 + .../templates/formtastic.css | 136 + .../templates/formtastic_changes.css | 10 + .../lib/formtastic.rb | 1236 +++++++ .../lib/justin_french/formtastic.rb | 10 + .../lib/locale/en.yml | 8 + .../rails/init.rb | 3 + .../spec/formtastic_spec.rb | 2900 +++++++++++++++++ .../spec/test_helper.rb | 14 + 25 files changed, 5017 insertions(+), 12 deletions(-) create mode 100644 generators/clearance_views/USAGE create mode 100644 generators/clearance_views/clearance_views_generator.rb create mode 100644 generators/clearance_views/templates/formtastic/passwords/edit.html.erb create mode 100644 generators/clearance_views/templates/formtastic/passwords/new.html.erb create mode 100644 generators/clearance_views/templates/formtastic/sessions/new.html.erb create mode 100644 generators/clearance_views/templates/formtastic/users/_inputs.html.erb create mode 100644 generators/clearance_views/templates/formtastic/users/new.html.erb create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/.specification create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/MIT-LICENSE create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/README.textile create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/Rakefile create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/formtastic_stylesheets_generator.rb create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/templates/formtastic.css create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/templates/formtastic_changes.css create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/formtastic.rb create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/justin_french/formtastic.rb create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/locale/en.yml create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/rails/init.rb create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/spec/formtastic_spec.rb create mode 100644 test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/spec/test_helper.rb diff --git a/.gitignore b/.gitignore index 20e7683c9..dea86d3cf 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ test/rails_root/log/*.log *.swp .rake_tasks test/rails_root/* +!test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1 *.gem diff --git a/CHANGELOG.textile b/CHANGELOG.textile index 3c27788dd..301161c29 100644 --- a/CHANGELOG.textile +++ b/CHANGELOG.textile @@ -1,3 +1,10 @@ +h2. 0.7.0 (08/04/2009) + +* Redirect signed in user who clicks confirmation link again. (Dan Croak) +* Redirect signed out user who clicks confirmation link again. (Dan Croak) +* Added signed_out? convenience method for controllers, helpers, views. (Dan +Croak) + h2. 0.6.9 (07/04/2009) * Added timestamps to create users migration. (Dan Croak) diff --git a/Rakefile b/Rakefile index b5fd3664c..33c827c14 100644 --- a/Rakefile +++ b/Rakefile @@ -5,8 +5,16 @@ require 'rake/testtask' require 'cucumber/rake/task' namespace :test do - Rake::TestTask.new(:all => ["generator:cleanup", - "generator:generate"]) do |task| + Rake::TestTask.new(:basic => ["generator:cleanup", + "generator:clearance", + "generator:clearance_features"]) do |task| + task.libs << "lib" + task.libs << "test" + task.pattern = "test/**/*_test.rb" + task.verbose = false + end + + Rake::TestTask.new(:views => ["generator:clearance_views"]) do |task| task.libs << "lib" task.libs << "test" task.pattern = "test/**/*_test.rb" @@ -17,9 +25,14 @@ namespace :test do t.cucumber_opts = "--format progress" t.feature_pattern = "test/rails_root/features/*.feature" end + + Cucumber::Rake::Task.new(:features_for_views) do |t| + t.cucumber_opts = "--format progress" + t.feature_pattern = "test/rails_root/features/*.feature" + end end -generators = %w(clearance clearance_features) +generators = %w(clearance clearance_features clearance_views) namespace :generator do desc "Cleans up the test app before running the generator" @@ -34,22 +47,36 @@ namespace :generator do FileList["test/rails_root/db/**/*"].each do |each| FileUtils.rm_rf(each) end + FileUtils.rm_rf("test/rails_root/vendor/plugins/clearance") FileUtils.mkdir_p("test/rails_root/vendor/plugins") clearance_root = File.expand_path(File.dirname(__FILE__)) system("ln -s #{clearance_root} test/rails_root/vendor/plugins/clearance") + + FileUtils.rm_rf("test/rails_root/app/views/passwords") + FileUtils.rm_rf("test/rails_root/app/views/sessions") + FileUtils.rm_rf("test/rails_root/app/views/users") end - desc "Run the generator on the tests" - task :generate do - generators.each do |generator| - system "cd test/rails_root && ./script/generate #{generator} && rake db:migrate db:test:prepare" - end + desc "Run the clearance generator" + task :clearance do + system "cd test/rails_root && ./script/generate clearance && rake db:migrate db:test:prepare" + end + + desc "Run the clearance features generator" + task :clearance_features do + system "cd test/rails_root && ./script/generate clearance_features" + end + + desc "Run the clearance views generator" + task :clearance_views do + system "cd test/rails_root && ./script/generate clearance_views" end end desc "Run the test suite" -task :default => ['test:all', 'test:features'] +task :default => ['test:basic', 'test:features', + 'test:views', 'test:features_for_views'] gem_spec = Gem::Specification.new do |gem_spec| gem_spec.name = "clearance" diff --git a/generators/clearance_features/clearance_features_generator.rb b/generators/clearance_features/clearance_features_generator.rb index f2b43ea53..477afd809 100644 --- a/generators/clearance_features/clearance_features_generator.rb +++ b/generators/clearance_features/clearance_features_generator.rb @@ -1,10 +1,10 @@ class ClearanceFeaturesGenerator < Rails::Generator::Base - + def manifest record do |m| m.directory File.join("features", "step_definitions") m.directory File.join("features", "support") - + ["features/step_definitions/clearance_steps.rb", "features/step_definitions/factory_girl_steps.rb", "features/support/paths.rb", @@ -16,5 +16,5 @@ def manifest end end end - + end diff --git a/generators/clearance_views/USAGE b/generators/clearance_views/USAGE new file mode 100644 index 000000000..e69de29bb diff --git a/generators/clearance_views/clearance_views_generator.rb b/generators/clearance_views/clearance_views_generator.rb new file mode 100644 index 000000000..6075ed825 --- /dev/null +++ b/generators/clearance_views/clearance_views_generator.rb @@ -0,0 +1,27 @@ +class ClearanceViewsGenerator < Rails::Generator::Base + + def manifest + record do |m| + strategy = "formtastic" + template_strategy = "erb" + + m.directory File.join("app", "views", "users") + m.file "#{strategy}/users/new.html.#{template_strategy}", + "app/views/users/new.html.#{template_strategy}" + m.file "#{strategy}/users/_inputs.html.#{template_strategy}", + "app/views/users/_inputs.html.#{template_strategy}" + + m.directory File.join("app", "views", "sessions") + m.file "#{strategy}/sessions/new.html.#{template_strategy}", + "app/views/sessions/new.html.#{template_strategy}" + + m.directory File.join("app", "views", "passwords") + m.file "#{strategy}/passwords/new.html.#{template_strategy}", + "app/views/passwords/new.html.#{template_strategy}" + m.file "#{strategy}/passwords/edit.html.#{template_strategy}", + "app/views/passwords/edit.html.#{template_strategy}" + end + end + +end + diff --git a/generators/clearance_views/templates/formtastic/passwords/edit.html.erb b/generators/clearance_views/templates/formtastic/passwords/edit.html.erb new file mode 100644 index 000000000..9cb7112e6 --- /dev/null +++ b/generators/clearance_views/templates/formtastic/passwords/edit.html.erb @@ -0,0 +1,21 @@ +

Change your password

+ +

+ Your password has been reset. Choose a new password below. +

+ +<% semantic_form_for(:user, + :url => user_password_path(@user, :token => @user.token), + :html => { :method => :put }) do |form| %> + <%= form.error_messages %> + <% form.inputs do -%> + <%= form.input :password, :as => :password, + :label => "Choose password" %> + <%= form.input :password_confirmation, :as => :password, + :label => "Confirm password" %> + <% end -%> + <% form.buttons do -%> + <%= form.commit_button "Save this password" %> + <% end -%> +<% end %> + diff --git a/generators/clearance_views/templates/formtastic/passwords/new.html.erb b/generators/clearance_views/templates/formtastic/passwords/new.html.erb new file mode 100644 index 000000000..4ac126938 --- /dev/null +++ b/generators/clearance_views/templates/formtastic/passwords/new.html.erb @@ -0,0 +1,15 @@ +

Reset your password

+ +

+ We will email you a link to reset your password. +

+ +<% semantic_form_for :password, :url => passwords_path do |form| -%> + <% form.inputs do -%> + <%= form.input :email, :label => "Email address" %> + <% end -%> + <% form.buttons do -%> + <%= form.commit_button "Reset password" %> + <% end -%> +<% end -%> + diff --git a/generators/clearance_views/templates/formtastic/sessions/new.html.erb b/generators/clearance_views/templates/formtastic/sessions/new.html.erb new file mode 100644 index 000000000..ad86f712a --- /dev/null +++ b/generators/clearance_views/templates/formtastic/sessions/new.html.erb @@ -0,0 +1,22 @@ +

Sign in

+ +<% semantic_form_for :session, :url => session_path do |form| %> + <% form.inputs do %> + <%= form.input :email %> + <%= form.input :password, :as => :password %> + <%= form.input :remember_me, :as => :boolean, :required => false %> + <% end %> + <% form.buttons do %> + <%= form.commit_button "Sign in" %> + <% end %> +<% end %> + + + diff --git a/generators/clearance_views/templates/formtastic/users/_inputs.html.erb b/generators/clearance_views/templates/formtastic/users/_inputs.html.erb new file mode 100644 index 000000000..aff79083d --- /dev/null +++ b/generators/clearance_views/templates/formtastic/users/_inputs.html.erb @@ -0,0 +1,6 @@ +<% form.inputs do %> + <%= form.input :email %> + <%= form.input :password %> + <%= form.input :password_confirmation, :label => "Confirm password" %> +<% end %> + diff --git a/generators/clearance_views/templates/formtastic/users/new.html.erb b/generators/clearance_views/templates/formtastic/users/new.html.erb new file mode 100644 index 000000000..be7f1dccd --- /dev/null +++ b/generators/clearance_views/templates/formtastic/users/new.html.erb @@ -0,0 +1,10 @@ +

Sign up

+ +<% semantic_form_for @user do |form| %> + <%= form.error_messages %> + <%= render :partial => "/users/inputs", :locals => { :form => form } %> + <% form.buttons do %> + <%= form.commit_button "Sign up" %> + <% end %> +<% end %> + diff --git a/test/rails_root/config/environment.rb b/test/rails_root/config/environment.rb index 221509259..76a5a6c82 100644 --- a/test/rails_root/config/environment.rb +++ b/test/rails_root/config/environment.rb @@ -8,6 +8,9 @@ :session_key => "_clearance_session", :secret => ['clearance', 'random', 'words', 'here'].map {|k| Digest::MD5.hexdigest(k) }.join } + config.gem "justinfrench-formtastic", + :lib => 'formtastic', + :source => 'http://gems.github.com' end DO_NOT_REPLY = "donotreply@example.com" diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/.specification b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/.specification new file mode 100644 index 000000000..65a9bf68e --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/.specification @@ -0,0 +1,67 @@ +--- !ruby/object:Gem::Specification +name: justinfrench-formtastic +version: !ruby/object:Gem::Version + version: 0.2.1 +platform: ruby +authors: +- Justin French +autorequire: formtastic +bindir: bin +cert_chain: [] + +date: 2009-06-17 00:00:00 -04:00 +default_executable: +dependencies: [] + +description: A Rails form builder plugin/gem with semantically rich and accessible markup +email: justin@indent.com.au +executables: [] + +extensions: [] + +extra_rdoc_files: +- README.textile +files: +- MIT-LICENSE +- README.textile +- Rakefile +- generators/formtastic_stylesheets/formtastic_stylesheets_generator.rb +- generators/formtastic_stylesheets/templates/formtastic.css +- generators/formtastic_stylesheets/templates/formtastic_changes.css +- lib/formtastic.rb +- lib/justin_french/formtastic.rb +- lib/locale/en.yml +- rails/init.rb +- spec/formtastic_spec.rb +- spec/test_helper.rb +has_rdoc: true +homepage: http://github.com/justinfrench/formtastic/tree/master +licenses: [] + +post_install_message: +rdoc_options: +- --charset=UTF-8 +require_paths: +- lib +required_ruby_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +required_rubygems_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +requirements: [] + +rubyforge_project: +rubygems_version: 1.3.4 +signing_key: +specification_version: 3 +summary: A Rails form builder plugin/gem with semantically rich and accessible markup +test_files: +- spec/formtastic_spec.rb +- spec/test_helper.rb diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/MIT-LICENSE b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/MIT-LICENSE new file mode 100644 index 000000000..b32f74184 --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2008 Justin French + +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. diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/README.textile b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/README.textile new file mode 100644 index 000000000..671350b54 --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/README.textile @@ -0,0 +1,383 @@ +h1. Formtastic + +Formtastic is a Rails FormBuilder DSL (with some other goodies) to make it far easier to create beautiful, semantically rich, syntactically awesome, readily stylable and wonderfully accessible HTML forms in your Rails applications. + +h2. The Story + +One day, I finally had enough, so I opened up my text editor, and wrote a DSL for how I'd like to author forms: + +
+  <% semantic_form_for @article do |form| %>
+
+    <% form.inputs :name => "Basic" do %>
+      <%= form.input :title %>
+      <%= form.input :body %>
+      <%= form.input :section %>
+      <%= form.input :publication_state, :as => :radio %>
+      <%= form.input :category %>
+      <%= form.input :allow_comments, :label => "Allow commenting on this article" %>
+    <% end %>
+
+    <% form.inputs :name => "Advanced" do %>
+      <%= form.input :keywords, :required => false, :hint => "Example: ruby, rails, forms" %>
+      <%= form.input :extract, :required => false %>
+      <%= form.input :description, :required => false %>
+      <%= form.input :url_title, :required => false %>
+    <% end %>
+
+    <% form.inputs :name => "Author", :for => :author do |author_form| %>
+      <%= author_form.input :first_name %>
+      <%= author_form.input :last_name %>
+    <% end %>
+
+    <% form.buttons do %>
+      <%= form.commit_button %>
+    <% end %>
+
+  <% end %>
+
+ +I also wrote the accompanying HTML output I expected, favoring something very similar to the fieldsets, lists and other semantic elements Aaron Gustafson presented in "Learning to Love Forms":http://www.slideshare.net/AaronGustafson/learning-to-love-forms-web-directions-south-07, hacking together enough Ruby to prove it could be done. + + +h2. It's better than _SomeOtherFormBuilder_ because... + +* it can handle @belongs_to@ associations (like Post belongs_to :author), rendering a select or set of radio inputs with choices from the parent model +* it can handle @has_many@ and @has_and_belongs_to_many@ associations (like Post has_many :tags), rendering a multi-select with choices from the child models +* it's Rails 2.3-ready (including nested forms) +* it has internationalization (I18n)! +* it's _really_ quick to get started with a basic form in place (4 lines), then go back to add in more detail if you need it +* there's heaps of elements, id and class attributes for you to hook in your CSS and JS +* it handles real world stuff like inline hints, inline error messages & help text +* it doesn't hijack or change any of the standard Rails form inputs, so you can still use them as expected (even mix and match) +* it's got absolutely awesome spec coverage +* there's a bunch of people using and working on it (it's not just one developer building half a solution) + + +h2. Why? + +* web apps = lots of forms +* forms are so friggin' boring to code +* semantically rich & accessible forms really are possible +* the "V" is way behind the "M" and "C" in Rails' MVC – it's the ugly sibling +* best practices and common patterns have to start somewhere +* i need a challenge + + +h2. Opinions + +* it should be easier to do things the right way than the wrong way +* sometimes _more mark-up_ is better +* elements and attribute hooks are _gold_ for stylesheet authors +* make the common things we do easy, yet still ensure uncommon things are still possible + + +h2. Installation + +You can (and should) get it as a gem: + +
+  gem install justinfrench-formtastic
+
+ +And then add it as a dependency in your environment.rb file: + +
+  config.gem "justinfrench-formtastic", 
+    :lib     => 'formtastic', 
+    :source  => 'http://gems.github.com'
+
+ +If you're a little more old school, install it as a plugin: + +
+  ./script/plugin install git://github.com/justinfrench/formtastic.git
+
+ + +h2. Usage + +Forms are really boring to code... you want to get onto the good stuff as fast as possible. + +This renders a set of inputs (one for _most_ columns in the database table, and one for each ActiveRecord belongs_to association), followed by a submit button: + +
+  <% semantic_form_for @user do |form| %>
+    <%= form.inputs %>
+    <%= form.buttons %>
+  <% end %>
+
+ +If you want to specify the order of the fields, skip some of the fields or even add in fields that Formtastic couldn't detect, you can pass in a list of field names to @inputs@ and list of button names to @buttons@: + +
+  <% semantic_form_for @user do |form| %>
+    <%= form.inputs :title, :body, :section, :categories, :created_at %>
+    <%= form.buttons :commit %>
+  <% end %>
+
+ +If you want control over the input type Formtastic uses for each field, you can expand the @inputs@ and @buttons@ blocks. This specifies the :section input should be a set of radio buttons (rather than the default select box), and that the :created_at field should be a string (rather than the default datetime selects): + +
+  <% semantic_form_for @post do |form| %>
+    <% form.inputs do %>
+      <%= form.input :title %>
+      <%= form.input :body %>
+      <%= form.input :section, :as => :radio %>
+      <%= form.input :categories %>
+      <%= form.input :created_at, :as => :string %>
+    <% end %>
+    <% form.buttons do %>
+      <%= form.commit_button %>
+    <% end %>
+  <% end %>
+
+ +If you want to customize the label text, or render some hint text below the field, specify which fields are required/optional, or break the form into two fieldsets, the DSL is pretty comprehensive: + +
+  <% semantic_form_for @post do |form| %>
+    <% form.inputs :name => "Basic", :id => "basic" do %>
+      <%= form.input :title %>
+      <%= form.input :body %>
+    <% end %>
+    <% form.inputs :name => "Advanced Options", :id => "advanced" do %>
+      <%= form.input :slug, :label => "URL Title", :hint => "Created automatically if left blank", :required => false %>
+      <%= form.input :section, :as => :radio %>
+      <%= form.input :user, :label => "Author", :label_method => :full_name,  %>
+      <%= form.input :categories, :required => false %>
+      <%= form.input :created_at, :as => :string, :label => "Publication Date", :required => false %>
+    <% end %>
+    <% form.buttons do %>
+      <%= form.commit_button %>
+    <% end %>
+  <% end %>
+
+ + +Nested forms (Rails 2.3) are also supported. You can do it in the Rails way: + +
+  <% semantic_form_for @post do |form| %>
+    <%= form.inputs :title, :body, :created_at %>
+    <% form.semantic_fields_for :author do |author| %>
+      <%= author.inputs :first_name, :last_name, :name => 'Author' %>
+    <% end %>
+    <%= form.buttons %>
+  <% end %>
+
+ +Or the Formtastic way with the @:for@ option: + +
+  <% semantic_form_for @post do |form| %>
+    <%= form.inputs :title, :body, :created_at %>
+    <%= form.inputs :first_name, :last_name, :for => :author, :name => "Author" %>
+    <%= form.buttons %>
+  <% end %>
+
+ +When working in has many association, you can even supply "%i" in your fieldset name that it will be properly interpolated with the child index. For example: + +
+  <% semantic_form_for @post do |form| %>
+    <%= form.inputs %>
+    <%= form.inputs :name => 'Category #%i', :for => :categories %>
+    <%= form.buttons %>
+  <% end %>
+
+ + +Customize HTML attributes for any input using the @:input_html@ option. Typically his is used to disable the input, change the size of a text field, change the rows in a textarea, or even to add a special class to an input to attach special behavior like "autogrow":http://plugins.jquery.com/project/autogrow textareas: + +
+  <% semantic_form_for @post do |form| %>
+    <%= form.input :title,      :input_html => { :size => 60 } %>
+    <%= form.input :body,       :input_html => { :class => 'autogrow' } %>
+    <%= form.input :created_at, :input_html => { :disabled => true } %>
+    <%= form.buttons %>
+  <% end %>
+
+ +The same can be done for buttons with the @:button_html@ option: + +
+  <% semantic_form_for @post do |form| %>
+    ...
+    <% form.buttons do %>
+      <%= form.commit_button :button_html => { :class => "primary" } %>
+    <% end %>
+  <% end %>
+
+ +Customize the HTML attributes for the @
  • @ wrapper around every input with the @:wrapper_html@ option hash. There's one special key in the hash (:class), which will actually _append_ your string of classes to the existing classes provided by Formtastic (like "required string error") + +
    +  <% semantic_form_for @post do |form| %>
    +    <%= form.input :title, :wrapper_html => { :class => "important" } %>
    +    <%= form.input :body %>
    +    <%= form.input :description, :wrapper_html => { :style => "display:none;" } %>
    +    ...
    +  <% end %>
    +
    + + + +h2. The Available Inputs + +* :select (a select menu) - default for ActiveRecord associations (belongs_to, has_many, has_and_belongs_to_many) +* :check_boxes (a set of check_box inputs) - alternative to :select has_many and has_and_belongs_to_many associations +* :radio (a set of radio inputs) - alternative to :select for ActiveRecord belongs_to associations +* :time_zone (a select input) - default for :string column types with 'time_zone' in the method name +* :password (a password input) - default for :string column types with 'password' in the method name +* :text (a textarea) - default for :text column types +* :date (a date select) - default for :date column types +* :datetime (a date and time select) - default for :datetime and :timestamp column types +* :time (a time select) - default for :time column types +* :boolean (a checkbox) - default for :boolean column types +* :string (a text field) - default for :string column types +* :numeric (a text field, like string) - default for :integer, :float and :decimal column types +* :file (a file field) - default for paperclip or attachment_fu attributes +* :country (a select menu of country names) - default for :string columns named "country", requires a country_select plugin to be installed +* :hidden (a hidden field) - creates a hidden field (added for compatibility) + + +The documentation is pretty good for each of these (what it does, what the output is, what the options are, etc) so go check it out. + + +h2. Configuration + +If you wish, put something like this in config/initializers/formtastic_config.rb: + +
    +  # Set the default text field size when input is a string. Default is 50
    +  Formtastic::SemanticFormBuilder.default_text_field_size = 30
    +
    +  # Should all fields be considered "required" by default
    +  # Defaults to true, see ValidationReflection notes below
    +  Formtastic::SemanticFormBuilder.all_fields_required_by_default = false
    +  
    +  # Set the string that will be appended to the labels/fieldsets which are required
    +  # It accepts string or procs and the default is a localized version of
    +  # '*'. In other words, if you configure formtastic.required
    +  # in your locale, it will replace the abbr title properly. But if you don't want to use
    +  # abbr tag, you can simply give a string as below
    +  Formtastic::SemanticFormBuilder.required_string = "(required)"
    +  
    +  # Set the string that will be appended to the labels/fieldsets which are optional
    +  # Defaults to an empty string ("") and also accepts procs (see required_string above)
    +  Formtastic::SemanticFormBuilder.optional_string = "(optional)"
    +
    +  # Set the way inline errors will be displayed.
    +  # Defaults to :sentence, valid options are :sentence, :list and :none
    +  Formtastic::SemanticFormBuilder.inline_errors = :list
    +
    +  # Set the method to call on label text to transform or format it for human-friendly
    +  # reading when formtastic is user without object. Defaults to :humanize.
    +  Formtastic::SemanticFormBuilder.label_str_method = :titleize
    +
    +  # Set the array of methods to try calling on parent objects in :select and :radio inputs
    +  # for the text inside each @
    + + +h2. Internationalization (I18n) + +Supports I18n! ActiveRecord object names and attributes are, by default, taken from calling @object.human_name and @object.human_attribute_name(attr) respectively. There are a few words specific to Formtastic that can be translated. See lib/locale/en.yml for more information. + + +h2. ValidationReflection plugin + +If you have the "ValidationReflection":http://github.com/redinger/validation_reflection plugin installed, you won't have to specify the :required option (it checks the validations on the model instead). + + +h2. Status + +*THINGS ARE GOING TO CHANGE A BIT BEFORE WE HIT 1.0.* + +It's a work in progress and a bit rough around the edges still, but I hope you try it and offer some suggestions and improvements anyway. + +On the plus side, it has a comprehensive spec suite and contributions from at least ten independent developers. + +"Wishlist":http://wiki.github.com/justinfrench/formtastic/wishlist on the wiki is serving as pretty good documentation for the roadmap to 1.0 and beyond right now, but I'll work on getting a real tracking system or something happening soon. + + +h2. Dependencies + +There are none, but... + +* if you have the "ValidationReflection":http://github.com/redinger/validation_reflection plugin is installed, you won't have to specify the :required option (it checks the validations on the model instead) +* if you want to use the :country input, you'll need to install the "iso-3166-country-select plugin":http://github.com/rails/iso-3166-country-select (or any other country_select plugin with the same API) +* rspec, rspec_hpricot_matchers and rcov gems (plus any of their own dependencies) are required for the test suite + + +h2. Compatibility + +I'm only testing Formtastic with the latest Rails 2.2.x stable release, and it should be fine under Rails 2.3 as well (including nested forms). Patches are welcome to allow backwards compatibility, but I don't have the energy! + + + +h2. What about Stylesheets? + +A proof-of-concept (very much a work-in-progress) stylesheet is provided which you can include in your layout. Customization is best achieved by overriding these styles in an additional stylesheet so that the Formtastic styles can be updated without clobbering your changes. + +1. Use the generator to copy the formtastic.css and formtastic_changes.css into your public directory + +
    +./script/generate formtastic_stylesheets
    +
    + +2. Add both formtastic.css and formtastic_changes.css to your layout: + +
    +<%= stylesheet_link_tag "formtastic" %>
    +<%= stylesheet_link_tag "formtastic_changes" %>
    +
    + + +h2. Contributors + +Formtastic is maintained by "Justin French":http://justinfrench.com and "José Valim":http://github.com/josevalim, but it wouldn't be as awesome as it is today if it weren't for the wonderful contributions of these fine, fine coders. + +* "Jeff Smick":http://github.com/sprsquish +* "Tien Dung":http://github.com/tiendung +* "Mark Mansour":http://stateofflux.com +* "Andy Pearson":http://github.com/andypearson +* "negonicrac":http://github.com/negonicrac +* "Xavier Shay":http://rhnh.net +* "Pat Allan":http://github.com/freelancing-god +* "Gareth Townsend":http://github.com/quamen +* "Sascha Hoellger":http://github.com/mitnal +* "Andrew Carpenter":http://github.com/andrewcarpenter +* "Jack Dempsey":http://github.com/jackdempsey/ +* "Greg Fitzgerald":http://github.com/gregf/ +* "Hector E. Gomez Morales":http://github.com/hectoregm +* "Ben Hamill":http://blog.benhamill.com/ +* "Simon Chiu":http://github.com/tolatomeow +* "Bin Dong":http://github.com/dongbin + + +h2. Hey, join the Google group! + +Please join the "Formtastic Google Group":http://groups.google.com.au/group/formtastic, especially if you'd like to talk about a new feature, or report a bug. + + +h2. Project Info + +Formtastic is hosted on Github: http://github.com/justinfrench/formtastic/, where your contributions, forkings, comments and feedback are greatly welcomed. + + +Copyright (c) 2007-2008 Justin French, released under the MIT license. diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/Rakefile b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/Rakefile new file mode 100644 index 000000000..345272503 --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/Rakefile @@ -0,0 +1,58 @@ +require 'rake' +require 'rake/rdoctask' +require 'spec/rake/spectask' + +begin + GEM = "formtastic" + AUTHOR = "Justin French" + EMAIL = "justin@indent.com.au" + SUMMARY = "A Rails form builder plugin/gem with semantically rich and accessible markup" + HOMEPAGE = "http://github.com/justinfrench/formtastic/tree/master" + + require 'jeweler' + Jeweler::Tasks.new do |s| + s.name = GEM + s.summary = SUMMARY + s.email = EMAIL + s.homepage = HOMEPAGE + s.description = SUMMARY + s.author = AUTHOR + + s.require_path = 'lib' + s.autorequire = GEM + s.files = %w(MIT-LICENSE README.textile Rakefile) + Dir.glob("{rails,lib,generators,spec}/**/*") + end +rescue LoadError + puts "Jeweler, or one of its dependencies, is not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com" +end + +desc 'Default: run unit specs.' +task :default => :spec + +desc 'Test the formtastic plugin.' +Spec::Rake::SpecTask.new('spec') do |t| + t.spec_files = FileList['spec/**/*_spec.rb'] + t.spec_opts = ["-c"] +end + +desc 'Test the formtastic plugin with specdoc formatting and colors' +Spec::Rake::SpecTask.new('specdoc') do |t| + t.spec_files = FileList['spec/**/*_spec.rb'] + t.spec_opts = ["--format specdoc", "-c"] +end + +desc 'Generate documentation for the formtastic plugin.' +Rake::RDocTask.new(:rdoc) do |rdoc| + rdoc.rdoc_dir = 'rdoc' + rdoc.title = 'Formtastic' + rdoc.options << '--line-numbers' << '--inline-source' + rdoc.rdoc_files.include('README.textile') + rdoc.rdoc_files.include('lib/**/*.rb') +end + +desc "Run all examples with RCov" +Spec::Rake::SpecTask.new('examples_with_rcov') do |t| + t.spec_files = FileList['spec/**/*_spec.rb'] + t.rcov = true + t.rcov_opts = ['--exclude', 'spec,Library'] +end diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/formtastic_stylesheets_generator.rb b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/formtastic_stylesheets_generator.rb new file mode 100644 index 000000000..be40439f8 --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/formtastic_stylesheets_generator.rb @@ -0,0 +1,21 @@ +class FormtasticStylesheetsGenerator < Rails::Generator::Base + + def initialize(*runtime_args) + super + end + + def manifest + record do |m| + m.directory File.join('public', 'stylesheets') + m.template 'formtastic.css', File.join('public', 'stylesheets', 'formtastic.css') + m.template 'formtastic_changes.css', File.join('public', 'stylesheets', 'formtastic_changes.css') + end + end + + protected + + def banner + %{Usage: #{$0} #{spec.name}\nCopies formtastic.css and formtastic_changes.css to public/} + end + +end \ No newline at end of file diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/templates/formtastic.css b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/templates/formtastic.css new file mode 100644 index 000000000..122fd9b83 --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/templates/formtastic.css @@ -0,0 +1,136 @@ +/* ------------------------------------------------------------------------------------------------- + +It's *strongly* suggested that you don't modify this file. Instead, load a new stylesheet after +this one in your layouts (eg formtastic_changes.css) and override the styles to suit your needs. +This will allow you to update formtastic.css with new releases without clobbering your own changes. + +This stylesheet forms part of the Formtastic Rails Plugin +(c) 2008 Justin French + +--------------------------------------------------------------------------------------------------*/ + + +/* NORMALIZE AND RESET - obviously inspired by Yahoo's reset.css, but scoped to just form.formtastic +--------------------------------------------------------------------------------------------------*/ +form.formtastic, form.formtastic ul, form.formtastic ol, form.formtastic li, form.formtastic fieldset, form.formtastic legend, form.formtastic input, form.formtastic textarea, form.formtastic select, form.formtastic p { margin:0; padding:0; } +form.formtastic fieldset { border:0; } +form.formtastic em, form.formtastic strong { font-style:normal; font-weight:normal; } +form.formtastic ol, form.formtastic ul { list-style:none; } +form.formtastic abbr, form.formtastic acronym { border:0; font-variant:normal; } +form.formtastic input, form.formtastic textarea, form.formtastic select { font-family:inherit; font-size:inherit; font-weight:inherit; } +form.formtastic input, form.formtastic textarea, form.formtastic select { font-size:100%; } +form.formtastic legend { color:#000; } + + +/* FIELDSETS & LISTS +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset { } +form.formtastic fieldset.inputs { } +form.formtastic fieldset.buttons { padding-left:25%; } +form.formtastic fieldset ol { } +form.formtastic fieldset.buttons li { float:left; padding-right:0.5em; } + +/* clearfixing the fieldsets */ +form.formtastic fieldset { display: inline-block; } +form.formtastic fieldset:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } +html[xmlns] form.formtastic fieldset { display: block; } +* html form.formtastic fieldset { height: 1%; } + + +/* INPUT LIs +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li { margin-bottom:1.5em; } + +/* clearfixing the li's */ +form.formtastic fieldset ol li { display: inline-block; } +form.formtastic fieldset ol li:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } +html[xmlns] form.formtastic fieldset ol li { display: block; } +* html form.formtastic fieldset ol li { height: 1%; } + +form.formtastic fieldset ol li.required { } +form.formtastic fieldset ol li.optional { } +form.formtastic fieldset ol li.error { } + + +/* LABELS +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li label { display:block; width:25%; float:left; padding-top:.2em; } +form.formtastic fieldset ol li li label { line-height:100%; padding-top:0; } +form.formtastic fieldset ol li li label input { line-height:100%; vertical-align:middle; margin-top:-0.1em;} + + +/* NESTED FIELDSETS AND LEGENDS (radio, check boxes and date/time inputs use nested fieldsets) +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li fieldset { position:relative; } +form.formtastic fieldset ol li fieldset legend { position:absolute; width:25%; padding-top:0.1em; } +form.formtastic fieldset ol li fieldset legend span { position:absolute; } +form.formtastic fieldset ol li fieldset ol { float:left; width:74%; margin:0; padding:0 0 0 25%; } +form.formtastic fieldset ol li fieldset ol li { padding:0; border:0; } + + +/* INLINE HINTS +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li p.inline-hints { color:#666; margin:0.5em 0 0 25%; } + + +/* INLINE ERRORS +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li p.inline-errors { color:#cc0000; margin:0.5em 0 0 25%; } +form.formtastic fieldset ol li ul.errors { color:#cc0000; margin:0.5em 0 0 25%; list-style:square; } +form.formtastic fieldset ol li ul.errors li { padding:0; border:none; display:list-item; } + + +/* STRING & NUMERIC OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li.string input { width:74%; } +form.formtastic fieldset ol li.numeric input { width:74%; } + + +/* TEXTAREA OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li.text textarea { width:74%; } + + +/* HIDDEN OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li.hidden { display:none; } + + +/* BOOLEAN OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li.boolean label { padding-left:25%; width:auto; } +form.formtastic fieldset ol li.boolean label input { margin:0 0.5em 0 0.2em; } + + +/* RADIO OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li.radio { } +form.formtastic fieldset ol li.radio fieldset ol { margin-bottom:-0.6em; } +form.formtastic fieldset ol li.radio fieldset ol li { margin:0.1em 0 0.5em 0; } +form.formtastic fieldset ol li.radio fieldset ol li label { float:none; width:100%; } +form.formtastic fieldset ol li.radio fieldset ol li label input { margin-right:0.2em; } + + +/* CHECK BOXES (COLLECTION) OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li.check_boxes { } +form.formtastic fieldset ol li.check_boxes fieldset ol { margin-bottom:-0.6em; } +form.formtastic fieldset ol li.check_boxes fieldset ol li { margin:0.1em 0 0.5em 0; } +form.formtastic fieldset ol li.check_boxes fieldset ol li label { float:none; width:100%; } +form.formtastic fieldset ol li.check_boxes fieldset ol li label input { margin-right:0.2em; } + + + +/* DATE & TIME OVERRIDES +--------------------------------------------------------------------------------------------------*/ +form.formtastic fieldset ol li.date fieldset ol li, +form.formtastic fieldset ol li.time fieldset ol li, +form.formtastic fieldset ol li.datetime fieldset ol li { float:left; width:auto; margin:0 .3em 0 0; } + +form.formtastic fieldset ol li.date fieldset ol li label, +form.formtastic fieldset ol li.time fieldset ol li label, +form.formtastic fieldset ol li.datetime fieldset ol li label { display:none; } + +form.formtastic fieldset ol li.date fieldset ol li label input, +form.formtastic fieldset ol li.time fieldset ol li label input, +form.formtastic fieldset ol li.datetime fieldset ol li label input { display:inline; margin:0; padding:0; } diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/templates/formtastic_changes.css b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/templates/formtastic_changes.css new file mode 100644 index 000000000..608d4282f --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/generators/formtastic_stylesheets/templates/formtastic_changes.css @@ -0,0 +1,10 @@ +/* ------------------------------------------------------------------------------------------------- + +Load this stylesheet after formtastic.css in your layouts to override the CSS to suit your needs. +This will allow you to update formtastic.css with new releases without clobbering your own changes. + +For example, to make the inline hint paragraphs a little darker in color than the standard #666: + +form.formtastic fieldset ol li p.inline-hints { color:#333; } + +--------------------------------------------------------------------------------------------------*/ diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/formtastic.rb b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/formtastic.rb new file mode 100644 index 000000000..50d8a0b75 --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/formtastic.rb @@ -0,0 +1,1236 @@ +# Override the default ActiveRecordHelper behaviour of wrapping the input. +# This gets taken care of semantically by adding an error class to the LI tag +# containing the input. +ActionView::Base.field_error_proc = proc do |html_tag, instance_tag| + html_tag +end + +module Formtastic #:nodoc: + + class SemanticFormBuilder < ActionView::Helpers::FormBuilder + + @@default_text_field_size = 50 + @@all_fields_required_by_default = true + @@required_string = proc { %{*} } + @@optional_string = '' + @@inline_errors = :sentence + @@label_str_method = :humanize + @@collection_label_methods = %w[to_label display_name full_name name title username login value to_s] + @@inline_order = [ :input, :hints, :errors ] + @@file_methods = [ :file?, :public_filename ] + @@priority_countries = ["Australia", "Canada", "United Kingdom", "United States"] + + cattr_accessor :default_text_field_size, :all_fields_required_by_default, :required_string, + :optional_string, :inline_errors, :label_str_method, :collection_label_methods, + :inline_order, :file_methods, :priority_countries + + # Keeps simple mappings in a hash + INPUT_MAPPINGS = { + :string => :text_field, + :password => :password_field, + :numeric => :text_field, + :text => :text_area, + :file => :file_field + } + STRING_MAPPINGS = [ :string, :password, :numeric ] + + attr_accessor :template + + # Returns a suitable form input for the given +method+, using the database column information + # and other factors (like the method name) to figure out what you probably want. + # + # Options: + # + # * :as - override the input type (eg force a :string to render as a :password field) + # * :label - use something other than the method name as the label text, when false no label is printed + # * :required - specify if the column is required (true) or not (false) + # * :hint - provide some text to hint or help the user provide the correct information for a field + # * :input_html - provide options that will be passed down to the generated input + # * :wrapper_html - provide options that will be passed down to the li wrapper + # + # Input Types: + # + # Most inputs map directly to one of ActiveRecord's column types by default (eg string_input), + # but there are a few special cases and some simplification (:integer, :float and :decimal + # columns all map to a single numeric_input, for example). + # + # * :select (a select menu for associations) - default to association names + # * :check_boxes (a set of check_box inputs for associations) - alternative to :select has_many and has_and_belongs_to_many associations + # * :radio (a set of radio inputs for associations) - alternative to :select belongs_to associations + # * :time_zone (a select menu with time zones) + # * :password (a password input) - default for :string column types with 'password' in the method name + # * :text (a textarea) - default for :text column types + # * :date (a date select) - default for :date column types + # * :datetime (a date and time select) - default for :datetime and :timestamp column types + # * :time (a time select) - default for :time column types + # * :boolean (a checkbox) - default for :boolean column types (you can also have booleans as :select and :radio) + # * :string (a text field) - default for :string column types + # * :numeric (a text field, like string) - default for :integer, :float and :decimal column types + # * :country (a select menu of country names) - requires a country_select plugin to be installed + # * :hidden (a hidden field) - creates a hidden field (added for compatibility) + # + # Example: + # + # <% semantic_form_for @employee do |form| %> + # <% form.inputs do -%> + # <%= form.input :name, :label => "Full Name"%> + # <%= form.input :manager_id, :as => :radio %> + # <%= form.input :hired_at, :as => :date, :label => "Date Hired" %> + # <%= form.input :phone, :required => false, :hint => "Eg: +1 555 1234" %> + # <% end %> + # <% end %> + # + def input(method, options = {}) + options[:required] = method_required?(method) unless options.key?(:required) + options[:as] ||= default_input_type(method) + + html_class = [ options[:as], (options[:required] ? :required : :optional) ] + html_class << 'error' if @object && @object.respond_to?(:errors) && @object.errors.on(method.to_s) + + wrapper_html = options.delete(:wrapper_html) || {} + wrapper_html[:id] ||= generate_html_id(method) + wrapper_html[:class] = (html_class << wrapper_html[:class]).flatten.compact.join(' ') + + if [:boolean_select, :boolean_radio].include?(options[:as]) + ::ActiveSupport::Deprecation.warn(":as => :#{options[:as]} is deprecated, use :as => :#{options[:as].to_s[8..-1]} instead", caller[3..-1]) + end + + list_item_content = @@inline_order.map do |type| + send(:"inline_#{type}_for", method, options) + end.compact.join("\n") + + return template.content_tag(:li, list_item_content, wrapper_html) + end + + # Creates an input fieldset and ol tag wrapping for use around a set of inputs. It can be + # called either with a block (in which you can do the usual Rails form stuff, HTML, ERB, etc), + # or with a list of fields. These two examples are functionally equivalent: + # + # # With a block: + # <% semantic_form_for @post do |form| %> + # <% form.inputs do %> + # <%= form.input :title %> + # <%= form.input :body %> + # <% end %> + # <% end %> + # + # # With a list of fields: + # <% semantic_form_for @post do |form| %> + # <%= form.inputs :title, :body %> + # <% end %> + # + # # Output: + #
    + #
    + #
      + #
    1. ...
    2. + #
    3. ...
    4. + #
    + #
    + #
    + # + # === Quick Forms + # + # When called without a block or a field list, an input is rendered for each column in the + # model's database table, just like Rails' scaffolding. You'll obviously want more control + # than this in a production application, but it's a great way to get started, then come back + # later to customise the form with a field list or a block of inputs. Example: + # + # <% semantic_form_for @post do |form| %> + # <%= form.inputs %> + # <% end %> + # + # === Options + # + # All options (with the exception of :name) are passed down to the fieldset as HTML + # attributes (id, class, style, etc). If provided, the :name option is passed into a + # legend tag inside the fieldset (otherwise a legend is not generated). + # + # # With a block: + # <% semantic_form_for @post do |form| %> + # <% form.inputs :name => "Create a new post", :style => "border:1px;" do %> + # ... + # <% end %> + # <% end %> + # + # # With a list (the options must come after the field list): + # <% semantic_form_for @post do |form| %> + # <%= form.inputs :title, :body, :name => "Create a new post", :style => "border:1px;" %> + # <% end %> + # + # === It's basically a fieldset! + # + # Instead of hard-coding fieldsets & legends into your form to logically group related fields, + # use inputs: + # + # <% semantic_form_for @post do |f| %> + # <% f.inputs do %> + # <%= f.input :title %> + # <%= f.input :body %> + # <% end %> + # <% f.inputs :name => "Advanced", :id => "advanced" do %> + # <%= f.input :created_at %> + # <%= f.input :user_id, :label => "Author" %> + # <% end %> + # <% end %> + # + # # Output: + #
    + #
    + #
      + #
    1. ...
    2. + #
    3. ...
    4. + #
    + #
    + #
    + # Advanced + #
      + #
    1. ...
    2. + #
    3. ...
    4. + #
    + #
    + #
    + # + # === Nested attributes + # + # As in Rails, you can use semantic_fields_for to nest attributes: + # + # <% semantic_form_for @post do |form| %> + # <%= form.inputs :title, :body %> + # + # <% form.semantic_fields_for :author, @bob do |author_form| %> + # <% author_form.inputs do %> + # <%= author_form.input :first_name, :required => false %> + # <%= author_form.input :last_name %> + # <% end %> + # <% end %> + # <% end %> + # + # But this does not look formtastic! This is equivalent: + # + # <% semantic_form_for @post do |form| %> + # <%= form.inputs :title, :body %> + # <% form.inputs :for => [ :author, @bob ] do |author_form| %> + # <%= author_form.input :first_name, :required => false %> + # <%= author_form.input :last_name %> + # <% end %> + # <% end %> + # + # And if you don't need to give options to your input call, you could do it + # in just one line: + # + # <% semantic_form_for @post do |form| %> + # <%= form.inputs :title, :body %> + # <%= form.inputs :first_name, :last_name, :for => @bob %> + # <% end %> + # + # Just remember that calling inputs generates a new fieldset to wrap your + # inputs. If you have two separate models, but, semantically, on the page + # they are part of the same fieldset, you should use semantic_fields_for + # instead (just as you would do with Rails' form builder). + # + def inputs(*args, &block) + html_options = args.extract_options! + html_options[:class] ||= "inputs" + + if html_options[:for] + inputs_for_nested_attributes(args, html_options, &block) + elsif block_given? + field_set_and_list_wrapping(html_options, &block) + else + if @object && args.empty? + args = @object.class.reflections.map { |n,_| n if _.macro == :belongs_to } + args += @object.class.content_columns.map(&:name) + args -= %w[created_at updated_at created_on updated_on lock_version] + args.compact! + end + contents = args.map { |method| input(method.to_sym) } + + field_set_and_list_wrapping(html_options, contents) + end + end + alias :input_field_set :inputs + + # Creates a fieldset and ol tag wrapping for form buttons / actions as list items. + # See inputs documentation for a full example. The fieldset's default class attriute + # is set to "buttons". + # + # See inputs for html attributes and special options. + def buttons(*args, &block) + html_options = args.extract_options! + html_options[:class] ||= "buttons" + + if block_given? + field_set_and_list_wrapping(html_options, &block) + else + args = [:commit] if args.empty? + contents = args.map { |button_name| send(:"#{button_name}_button") } + field_set_and_list_wrapping(html_options, contents) + end + end + alias :button_field_set :buttons + + # Creates a submit input tag with the value "Save [model name]" (for existing records) or + # "Create [model name]" (for new records) by default: + # + # <%= form.commit_button %> => + # + # The value of the button text can be overridden: + # + # <%= form.commit_button "Go" %> => + # + # And you can pass html atributes down to the input, with or without the button text: + # + # <%= form.commit_button "Go" %> => + # <%= form.commit_button :class => "pretty" %> => + + def commit_button(*args) + value = args.first.is_a?(String) ? args.shift : save_or_create_button_text + options = args.shift || {} + button_html = options.delete(:button_html) || {} + template.content_tag(:li, self.submit(value, button_html), :class => "commit") + end + + # A thin wrapper around #fields_for to set :builder => Formtastic::SemanticFormBuilder + # for nesting forms: + # + # # Example: + # <% semantic_form_for @post do |post| %> + # <% post.semantic_fields_for :author do |author| %> + # <% author.inputs :name %> + # <% end %> + # <% end %> + # + # # Output: + #
    + #
    + #
      + #
    1. + #
    + #
    + #
    + # + def semantic_fields_for(record_or_name_or_array, *args, &block) + opts = args.extract_options! + opts.merge!(:builder => Formtastic::SemanticFormBuilder) + args.push(opts) + fields_for(record_or_name_or_array, *args, &block) + end + + # Generates the label for the input. It also accepts the same arguments as + # Rails label method. It has three options that are not supported by Rails + # label method: + # + # * :required - Appends an abbr tag if :required is true + # * :label - An alternative form to give the label content. Whenever label + # is false, a blank string is returned. + # * :as_span - When true returns a span tag with class label instead of a label element + # + # == Examples + # + # f.label :title # like in rails, except that it searches the label on I18n API too + # + # f.label :title, "Your post title" + # f.label :title, :label => "Your post title" # Added for formtastic API + # + # f.label :title, :required => true # Returns + # + def label(method, options_or_text=nil, options=nil) + if options_or_text.is_a?(Hash) + return if options_or_text[:label] == false + + options = options_or_text + text = options.delete(:label) + else + text = options_or_text + options ||= {} + end + + text ||= humanized_attribute_name(method) + text << required_or_optional_string(options.delete(:required)) + + if options.delete(:as_span) + options[:class] ||= 'label' + template.content_tag(:span, text, options) + else + super(method, text, options) + end + end + + # Generates error messages for the given method. Errors can be shown as list + # or as sentence. If :none is set, no error is shown. + # + # This method is also aliased as errors_on, so you can call on your custom + # inputs as well: + # + # semantic_form_for :post do |f| + # f.text_field(:body) + # f.errors_on(:body) + # end + # + def inline_errors_for(method, options=nil) #:nodoc: + return nil unless @object && @object.respond_to?(:errors) && [:sentence, :list].include?(@@inline_errors) + + errors = @object.errors.on(method.to_s) + send("error_#{@@inline_errors}", Array(errors)) unless errors.blank? + end + alias :errors_on :inline_errors_for + + protected + + # Deals with :for option when it's supplied to inputs methods. Additional + # options to be passed down to :for should be supplied using :for_options + # key. + # + # It should raise an error if a block with arity zero is given. + # + def inputs_for_nested_attributes(args, options, &block) + args << options.merge!(:parent => { :builder => self, :for => options[:for] }) + + fields_for_block = if block_given? + raise ArgumentError, 'You gave :for option with a block to inputs method, ' << + 'but the block does not accept any argument.' if block.arity <= 0 + + proc { |f| f.inputs(*args){ block.call(f) } } + else + proc { |f| f.inputs(*args) } + end + + fields_for_args = [options.delete(:for), options.delete(:for_options) || {}].flatten + semantic_fields_for(*fields_for_args, &fields_for_block) + end + + # Remove any Formtastic-specific options before passing the down options. + # + def set_options(options) + options.except(:value_method, :label_method, :collection, :required, :label, + :as, :hint, :input_html, :label_html, :value_as_class) + end + + # Create a default button text. If the form is working with a object, it + # defaults to "Create model" or "Save model" depending if we are working + # with a new_record or not. + # + # When not working with models, it defaults to "Submit object". + # + def save_or_create_button_text(prefix='Submit') #:nodoc: + if @object + prefix = @object.new_record? ? 'Create' : 'Save' + object_name = @object.class.human_name + else + object_name = @object_name.to_s.send(@@label_str_method) + end + + I18n.t(prefix.downcase, :default => prefix, :scope => [:formtastic]) << ' ' << object_name + end + + # Determins if the attribute (eg :title) should be considered required or not. + # + # * if the :required option was provided in the options hash, the true/false value will be + # returned immediately, allowing the view to override any guesswork that follows: + # + # * if the :required option isn't provided in the options hash, and the ValidationReflection + # plugin is installed (http://github.com/redinger/validation_reflection), true is returned + # if the validates_presence_of macro has been used in the class for this attribute, or false + # otherwise. + # + # * if the :required option isn't provided, and the plugin isn't available, the value of the + # configuration option @@all_fields_required_by_default is used. + # + def method_required?(attribute) #:nodoc: + if @object && @object.class.respond_to?(:reflect_on_all_validations) + attribute_sym = attribute.to_s.sub(/_id$/, '').to_sym + + @object.class.reflect_on_all_validations.any? do |validation| + validation.macro == :validates_presence_of && validation.name == attribute_sym + end + else + @@all_fields_required_by_default + end + end + + # A method that deals with most of inputs (:string, :password, :file, + # :textarea and :numeric). :select, :radio, :boolean and :datetime inputs + # are not handled by this method, since they need more detailed approach. + # + # If input_html is given as option, it's passed down to the input. + # + def input_simple(type, method, options) + html_options = options.delete(:input_html) || {} + html_options = default_string_options(method).merge(html_options) if STRING_MAPPINGS.include?(type) + + self.label(method, options.slice(:label, :required)) + + self.send(INPUT_MAPPINGS[type], method, html_options) + end + + # Outputs a hidden field inside the wrapper, which should be hidden with CSS. + # Additionals options can be given and will be sent straight to hidden input + # element. + # + def hidden_input(method, options) + self.hidden_field(method, set_options(options)) + end + + # Outputs a label and a select box containing options from the parent + # (belongs_to, has_many, has_and_belongs_to_many) association. If an association + # is has_many or has_and_belongs_to_many the select box will be set as multi-select + # and size = 5 + # + # Example (belongs_to): + # + # f.input :author + # + # + # + # + # Example (has_many): + # + # f.input :chapters + # + # + # + # + # Example (has_and_belongs_to_many): + # + # f.input :authors + # + # + # + # + # + # You can customize the options available in the select by passing in a collection (Array) of + # ActiveRecord objects through the :collection option. If not provided, the choices are found + # by inferring the parent's class name from the method name and simply calling find(:all) on + # it (VehicleOwner.find(:all) in the example above). + # + # Examples: + # + # f.input :author, :collection => @authors + # f.input :author, :collection => Author.find(:all) + # f.input :author, :collection => [@justin, @kate] + # f.input :author, :collection => {@justin.name => @justin.id, @kate.name => @kate.id} + # + # Note: This input looks for a label method in the parent association. + # + # You can customize the text label inside each option tag, by naming the correct method + # (:full_name, :display_name, :account_number, etc) to call on each object in the collection + # by passing in the :label_method option. By default the :label_method is whichever element of + # Formtastic::SemanticFormBuilder.collection_label_methods is found first. + # + # Examples: + # + # f.input :author, :label_method => :full_name + # f.input :author, :label_method => :display_name + # f.input :author, :label_method => :to_s + # f.input :author, :label_method => :label + # + # You can also customize the value inside each option tag, by passing in the :value_method option. + # Usage is the same as the :label_method option + # + # Examples: + # + # f.input :author, :value_method => :full_name + # f.input :author, :value_method => :display_name + # f.input :author, :value_method => :to_s + # f.input :author, :value_method => :value + # + # You can pass html_options to the select tag using :input_html => {} + # + # Examples: + # + # f.input :authors, :input_html => {:size => 20, :multiple => true} + # + # By default, all select inputs will have a blank option at the top of the list. You can add + # a prompt with the :prompt option, or disable the blank option with :include_blank => false. + # + def select_input(method, options) + collection = find_collection_for_column(method, options) + html_options = options.delete(:input_html) || {} + + unless options.key?(:include_blank) || options.key?(:prompt) + options[:include_blank] = true + end + + reflection = find_reflection(method) + if reflection && [ :has_many, :has_and_belongs_to_many ].include?(reflection.macro) + html_options[:multiple] ||= true + html_options[:size] ||= 5 + end + + input_name = generate_association_input_name(method) + self.label(input_name, options.slice(:label, :required)) + + self.select(input_name, collection, set_options(options), html_options) + end + alias :boolean_select_input :select_input + + # Outputs a timezone select input as Rails' time_zone_select helper. You + # can give priority zones as option. + # + # Examples: + # + # f.input :time_zone, :as => :time_zone, :priority_zones => /Australia/ + # + def time_zone_input(method, options) + html_options = options.delete(:input_html) || {} + + self.label(method, options.slice(:label, :required)) + + self.time_zone_select(method, options.delete(:priority_zones), set_options(options), html_options) + end + + # Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list + # items, one for each possible choice in the belongs_to association. Each li contains a + # label and a radio input. + # + # Example: + # + # f.input :author, :as => :radio + # + # Output: + # + #
    + # Author + #
      + #
    1. + # + #
    2. + #
    3. + # + #
    4. + #
    + #
    + # + # You can customize the options available in the set by passing in a collection (Array) of + # ActiveRecord objects through the :collection option. If not provided, the choices are found + # by inferring the parent's class name from the method name and simply calling find(:all) on + # it (Author.find(:all) in the example above). + # + # Examples: + # + # f.input :author, :as => :radio, :collection => @authors + # f.input :author, :as => :radio, :collection => Author.find(:all) + # f.input :author, :as => :radio, :collection => [@justin, @kate] + # + # You can also customize the text label inside each option tag, by naming the correct method + # (:full_name, :display_name, :account_number, etc) to call on each object in the collection + # by passing in the :label_method option. By default the :label_method is whichever element of + # Formtastic::SemanticFormBuilder.collection_label_methods is found first. + # + # Examples: + # + # f.input :author, :as => :radio, :label_method => :full_name + # f.input :author, :as => :radio, :label_method => :display_name + # f.input :author, :as => :radio, :label_method => :to_s + # f.input :author, :as => :radio, :label_method => :label + # + # Finally, you can set :value_as_class => true if you want that LI wrappers + # contains a class with the wrapped radio input value. + # + def radio_input(method, options) + collection = find_collection_for_column(method, options) + html_options = set_options(options).merge(options.delete(:input_html) || {}) + + input_name = generate_association_input_name(method) + value_as_class = options.delete(:value_as_class) + + list_item_content = collection.map do |c| + label = c.is_a?(Array) ? c.first : c + value = c.is_a?(Array) ? c.last : c + + li_content = template.content_tag(:label, + "#{self.radio_button(input_name, value, html_options)} #{label}", + :for => generate_html_id(input_name, value.to_s.downcase) + ) + + li_options = value_as_class ? { :class => value.to_s.downcase } : {} + template.content_tag(:li, li_content, li_options) + end + + field_set_and_list_wrapping_for_method(method, options, list_item_content) + end + alias :boolean_radio_input :radio_input + + # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list + # items (li), one for each fragment for the date (year, month, day). Each li contains a label + # (eg "Year") and a select box. See date_or_datetime_input for a more detailed output example. + # + # Some of Rails' options for select_date are supported, but not everything yet. + def date_input(method, options) + date_or_datetime_input(method, options.merge(:discard_hour => true)) + end + + + # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list + # items (li), one for each fragment for the date (year, month, day, hour, min, sec). Each li + # contains a label (eg "Year") and a select box. See date_or_datetime_input for a more + # detailed output example. + # + # Some of Rails' options for select_date are supported, but not everything yet. + def datetime_input(method, options) + date_or_datetime_input(method, options) + end + + + # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list + # items (li), one for each fragment for the time (hour, minute, second). Each li contains a label + # (eg "Hour") and a select box. See date_or_datetime_input for a more detailed output example. + # + # Some of Rails' options for select_time are supported, but not everything yet. + def time_input(method, options) + date_or_datetime_input(method, options.merge(:discard_year => true, :discard_month => true, :discard_day => true)) + end + + + #
    + # Created At + #
      + #
    1. + # + # + #
    2. + #
    3. + # + # + #
    4. + #
    5. + # + # + #
    6. + #
    + #
    + # + # This is an absolute abomination, but so is the official Rails select_date(). + # + def date_or_datetime_input(method, options) + position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 } + inputs = options.delete(:order) || I18n.translate(:'date.order') || [:year, :month, :day] + + time_inputs = [:hour, :minute] + time_inputs << [:second] if options[:include_seconds] + + list_items_capture = "" + hidden_fields_capture = "" + + # Gets the datetime object. It can be a Fixnum, Date or Time, or nil. + datetime = @object ? @object.send(method) : nil + html_options = options.delete(:input_html) || {} + + (inputs + time_inputs).each do |input| + html_id = generate_html_id(method, "#{position[input]}i") + field_name = "#{method}(#{position[input]}i)" + if options["discard_#{input}".intern] + break if time_inputs.include?(input) + + hidden_value = datetime.respond_to?(input) ? datetime.send(input) : datetime + hidden_fields_capture << template.hidden_field_tag("#{@object_name}[#{field_name}]", (hidden_value || 1), :id => html_id) + else + opts = set_options(options).merge(:prefix => @object_name, :field_name => field_name) + item_label_text = I18n.t(input.to_s, :default => input.to_s.humanize, :scope => [:datetime, :prompts]) + + list_items_capture << template.content_tag(:li, + template.content_tag(:label, item_label_text, :for => html_id) + + template.send("select_#{input}".intern, datetime, opts, html_options.merge(:id => html_id)) + ) + end + end + + hidden_fields_capture + field_set_and_list_wrapping_for_method(method, options, list_items_capture) + end + + + # Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list + # items, one for each possible choice in the belongs_to association. Each li contains a + # label and a check_box input. + # + # This is an alternative for has many and has and belongs to many associations. + # + # Example: + # + # f.input :author, :as => :check_boxes + # + # Output: + # + #
    + # Authors + #
      + #
    1. + # + # + #
    2. + #
    3. + # + # + #
    4. + #
    + #
    + # + # Notice that the value of the checkbox is the same as the id and the hidden + # field has empty value. You can override the hidden field value using the + # unchecked_value option. + # + # You can customize the options available in the set by passing in a collection (Array) of + # ActiveRecord objects through the :collection option. If not provided, the choices are found + # by inferring the parent's class name from the method name and simply calling find(:all) on + # it (Author.find(:all) in the example above). + # + # Examples: + # + # f.input :author, :as => :check_boxes, :collection => @authors + # f.input :author, :as => :check_boxes, :collection => Author.find(:all) + # f.input :author, :as => :check_boxes, :collection => [@justin, @kate] + # + # You can also customize the text label inside each option tag, by naming the correct method + # (:full_name, :display_name, :account_number, etc) to call on each object in the collection + # by passing in the :label_method option. By default the :label_method is whichever element of + # Formtastic::SemanticFormBuilder.collection_label_methods is found first. + # + # Examples: + # + # f.input :author, :as => :check_boxes, :label_method => :full_name + # f.input :author, :as => :check_boxes, :label_method => :display_name + # f.input :author, :as => :check_boxes, :label_method => :to_s + # f.input :author, :as => :check_boxes, :label_method => :label + # + # You can set :value_as_class => true if you want that LI wrappers contains + # a class with the wrapped checkbox input value. + # + def check_boxes_input(method, options) + collection = find_collection_for_column(method, options) + html_options = options.delete(:input_html) || {} + + input_name = generate_association_input_name(method) + value_as_class = options.delete(:value_as_class) + unchecked_value = options.delete(:unchecked_value) || '' + html_options = { :name => "#{@object_name}[#{input_name}][]" }.merge(html_options) + + list_item_content = collection.map do |c| + label = c.is_a?(Array) ? c.first : c + value = c.is_a?(Array) ? c.last : c + + html_options.merge!(:id => generate_html_id(input_name, value.to_s.downcase)) + + li_content = template.content_tag(:label, + "#{self.check_box(input_name, html_options, value, unchecked_value)} #{label}", + :for => html_options[:id] + ) + + li_options = value_as_class ? { :class => value.to_s.downcase } : {} + template.content_tag(:li, li_content, li_options) + end + + field_set_and_list_wrapping_for_method(method, options, list_item_content) + end + + + # Outputs a country select input, wrapping around a regular country_select helper. + # Rails doesn't come with a country_select helper by default any more, so you'll need to install + # the "official" plugin, or, if you wish, any other country_select plugin that behaves in the + # same way. + # + # The Rails plugin iso-3166-country-select plugin can be found "here":http://github.com/rails/iso-3166-country-select. + # + # By default, Formtastic includes a handfull of english-speaking countries as "priority counties", + # which you can change to suit your market and user base (see README for more info on config). + # + # Examples: + # f.input :location, :as => :country # use Formtastic::SemanticFormBuilder.priority_countries array for the priority countries + # f.input :location, :as => :country, :priority_countries => /Australia/ # set your own + # + def country_input(method, options) + raise "To use the :country input, please install a country_select plugin, like this one: http://github.com/rails/iso-3166-country-select" unless self.respond_to?(:country_select) + + html_options = options.delete(:input_html) || {} + priority_countries = options.delete(:priority_countries) || @@priority_countries + + self.label(method, options.slice(:label, :required)) + + self.country_select(method, priority_countries, set_options(options), html_options) + end + + + # Outputs a label containing a checkbox and the label text. The label defaults + # to the column name (method name) and can be altered with the :label option. + # :checked_value and :unchecked_value options are also available. + # + def boolean_input(method, options) + html_options = options.delete(:input_html) || {} + + input = self.check_box(method, set_options(options).merge(html_options), + options.delete(:checked_value) || '1', options.delete(:unchecked_value) || '0') + + label = options.delete(:label) || humanized_attribute_name(method) + self.label(method, input + label, options.slice(:required)) + end + + # Generates an input for the given method using the type supplied with :as. + # + # If the input is included in INPUT_MAPPINGS, it uses input_simple + # implementation which maps most of the inputs. All others have specific + # code and then a proper handler should be called (like radio_input) for + # :radio types. + # + def inline_input_for(method, options) + input_type = options.delete(:as) + + if INPUT_MAPPINGS.key?(input_type) + input_simple(input_type, method, options) + else + send("#{input_type}_input", method, options) + end + end + + # Generates hints for the given method using the text supplied in :hint. + # + def inline_hints_for(method, options) #:nodoc: + return if options[:hint].blank? + template.content_tag(:p, options[:hint], :class => 'inline-hints') + end + + # Creates an error sentence by calling to_sentence on the errors array. + # + def error_sentence(errors) #:nodoc: + template.content_tag(:p, errors.to_sentence.untaint, :class => 'inline-errors') + end + + # Creates an error li list. + # + def error_list(errors) #:nodoc: + list_elements = [] + errors.each do |error| + list_elements << template.content_tag(:li, error.untaint) + end + template.content_tag(:ul, list_elements.join("\n"), :class => 'errors') + end + + # Generates the required or optional string. If the value set is a proc, + # it evaluates the proc first. + # + def required_or_optional_string(required) #:nodoc: + string_or_proc = case required + when true + @@required_string + when false + @@optional_string + else + required + end + + if string_or_proc.is_a?(Proc) + string_or_proc.call + else + string_or_proc.to_s + end + end + + # Generates a fieldset and wraps the content in an ordered list. When working + # with nested attributes (in Rails 2.3), it allows %i as interpolation option + # in :name. So you can do: + # + # f.inputs :name => 'Task #%i', :for => :tasks + # + # And it will generate a fieldset for each task with legend 'Task #1', 'Task #2', + # 'Task #3' and so on. + # + def field_set_and_list_wrapping(html_options, contents='', &block) #:nodoc: + legend = html_options.delete(:name).to_s + legend %= parent_child_index(html_options[:parent]) if html_options[:parent] + legend = template.content_tag(:legend, template.content_tag(:span, legend)) unless legend.blank? + + contents = template.capture(&block) if block_given? + + # Ruby 1.9: String#to_s behavior changed, need to make an explicit join. + contents = contents.join if contents.respond_to?(:join) + fieldset = template.content_tag(:fieldset, + legend + template.content_tag(:ol, contents), + html_options.except(:builder, :parent) + ) + + template.concat(fieldset) if block_given? + fieldset + end + + # Also generates a fieldset and an ordered list but with label based in + # method. This methods is currently used by radio and datetime inputs. + # + def field_set_and_list_wrapping_for_method(method, options, contents) + contents = contents.join if contents.respond_to?(:join) + + template.content_tag(:fieldset, + %{#{self.label(method, options.slice(:label, :required).merge!(:as_span => true))}} + + template.content_tag(:ol, contents) + ) + end + + # For methods that have a database column, take a best guess as to what the input method + # should be. In most cases, it will just return the column type (eg :string), but for special + # cases it will simplify (like the case of :integer, :float & :decimal to :numeric), or do + # something different (like :password and :select). + # + # If there is no column for the method (eg "virtual columns" with an attr_accessor), the + # default is a :string, a similar behaviour to Rails' scaffolding. + # + def default_input_type(method) #:nodoc: + return :string if @object.nil? + + column = @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute) + + if column + # handle the special cases where the column type doesn't map to an input method + return :time_zone if column.type == :string && method.to_s =~ /time_zone/ + return :select if column.type == :integer && method.to_s =~ /_id$/ + return :datetime if column.type == :timestamp + return :numeric if [:integer, :float, :decimal].include?(column.type) + return :password if column.type == :string && method.to_s =~ /password/ + return :country if column.type == :string && method.to_s =~ /country/ + + # otherwise assume the input name will be the same as the column type (eg string_input) + return column.type + else + obj = @object.send(method) if @object.respond_to?(method) + + return :select if find_reflection(method) + return :file if obj && @@file_methods.any? { |m| obj.respond_to?(m) } + return :password if method.to_s =~ /password/ + return :string + end + end + + # Used by select and radio inputs. The collection can be retrieved by + # three ways: + # + # * Explicitly provided through :collection + # * Retrivied through an association + # * Or a boolean column, which will generate a localized { "Yes" => true, "No" => false } hash. + # + # If the collection is not a hash or an array of strings, fixnums or arrays, + # we use label_method and value_method to retreive an array with the + # appropriate label and value. + # + def find_collection_for_column(column, options) + reflection = find_reflection(column) + + collection = if options[:collection] + options.delete(:collection) + elsif reflection || column.to_s =~ /_id$/ + parent_class = if reflection + reflection.klass + else + ::ActiveSupport::Deprecation.warn("The _id way of doing things is deprecated. Please use the association method (#{column.to_s.sub(/_id$/,'')})", caller[3..-1]) + column.to_s.sub(/_id$/,'').camelize.constantize + end + + parent_class.find(:all) + else + create_boolean_collection(options) + end + + collection = collection.to_a if collection.instance_of?(Hash) + + # Return if we have an Array of strings, fixnums or arrays + return collection if collection.instance_of?(Array) && + [Array, Fixnum, String, Symbol].include?(collection.first.class) + + label = options.delete(:label_method) || detect_label_method(collection) + value = options.delete(:value_method) || :id + + collection.map { |o| [o.send(label), o.send(value)] } + end + + # Detected the label collection method when none is supplied using the + # values set in @@collection_label_methods. + # + def detect_label_method(collection) #:nodoc: + @@collection_label_methods.detect { |m| collection.first.respond_to?(m) } + end + + # Returns a hash to be used by radio and select inputs when a boolean field + # is provided. + # + def create_boolean_collection(options) + options[:true] ||= I18n.t('yes', :default => 'Yes', :scope => [:formtastic]) + options[:false] ||= I18n.t('no', :default => 'No', :scope => [:formtastic]) + options[:value_as_class] = true unless options.key?(:value_as_class) + + { options.delete(:true) => true, options.delete(:false) => false } + end + + # Used by association inputs (select, radio) to generate the name that should + # be used for the input + # + # belongs_to :author; f.input :author; will generate 'author_id' + # has_many :authors; f.input :authors; will generate 'author_ids' + # has_and_belongs_to_many will act like has_many + # + def generate_association_input_name(method) + if reflection = find_reflection(method) + if [:has_and_belongs_to_many, :has_many].include?(reflection.macro) + "#{method.to_s.singularize}_ids" + else + "#{method}_id" + end + else + method + end + end + + # If an association method is passed in (f.input :author) try to find the + # reflection object. + # + def find_reflection(method) + @object.class.reflect_on_association(method) if @object.class.respond_to?(:reflect_on_association) + end + + # Generates default_string_options by retrieving column information from + # the database. + # + def default_string_options(method) #:nodoc: + column = @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute) + + if column.nil? || column.limit.nil? + { :size => @@default_text_field_size } + else + { :maxlength => column.limit, :size => [column.limit, @@default_text_field_size].min } + end + end + + # Generate the html id for the li tag. + # It takes into account options[:index] and @auto_index to generate li + # elements with appropriate index scope. It also sanitizes the object + # and method names. + # + def generate_html_id(method_name, value='input') + if options.has_key?(:index) + index = "_#{options[:index]}" + elsif defined?(@auto_index) + index = "_#{@auto_index}" + else + index = "" + end + sanitized_method_name = method_name.to_s.sub(/\?$/,"") + + "#{sanitized_object_name}#{index}_#{sanitized_method_name}_#{value}" + end + + # Gets the nested_child_index value from the parent builder. In Rails 2.3 + # it always returns a fixnum. In next versions it returns a hash with each + # association that the parent builds. + # + def parent_child_index(parent) + duck = parent[:builder].instance_variable_get('@nested_child_index') + + if duck.is_a?(Hash) + child = parent[:for] + child = child.first if child.respond_to?(:first) + duck[child].to_i + 1 + else + duck.to_i + 1 + end + end + + def sanitized_object_name + @sanitized_object_name ||= @object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "") + end + + def humanized_attribute_name(method) + if @object && @object.class.respond_to?(:human_attribute_name) + @object.class.human_attribute_name(method.to_s) + else + method.to_s.send(@@label_str_method) + end + end + + end + + # Wrappers around form_for (etc) with :builder => SemanticFormBuilder. + # + # * semantic_form_for(@post) + # * semantic_fields_for(@post) + # * semantic_form_remote_for(@post) + # * semantic_remote_form_for(@post) + # + # Each of which are the equivalent of: + # + # * form_for(@post, :builder => Formtastic::SemanticFormBuilder)) + # * fields_for(@post, :builder => Formtastic::SemanticFormBuilder)) + # * form_remote_for(@post, :builder => Formtastic::SemanticFormBuilder)) + # * remote_form_for(@post, :builder => Formtastic::SemanticFormBuilder)) + # + # Example Usage: + # + # <% semantic_form_for @post do |f| %> + # <%= f.input :title %> + # <%= f.input :body %> + # <% end %> + # + # The above examples use a resource-oriented style of form_for() helper where only the @post + # object is given as an argument, but the generic style is also supported if you really want it, + # as is forms with inline objects (Post.new) rather than objects with instance variables (@post): + # + # <% semantic_form_for :post, @post, :url => posts_path do |f| %> + # ... + # <% end %> + # + # <% semantic_form_for :post, Post.new, :url => posts_path do |f| %> + # ... + # <% end %> + # + # The shorter, resource-oriented style is most definitely preferred, and has recieved the most + # testing to date. + # + # Please note: Although it's possible to call Rails' built-in form_for() helper without an + # object, all semantic forms *must* have an object (either Post.new or @post), as Formtastic + # has too many dependencies on an ActiveRecord object being present. + # + module SemanticFormHelper + @@builder = Formtastic::SemanticFormBuilder + + # cattr_accessor :builder + def self.builder=(val) + @@builder = val + end + + [:form_for, :fields_for, :form_remote_for, :remote_form_for].each do |meth| + src = <<-END_SRC + def semantic_#{meth}(record_or_name_or_array, *args, &proc) + options = args.extract_options! + options[:builder] = @@builder + options[:html] ||= {} + + class_names = options[:html][:class] ? options[:html][:class].split(" ") : [] + class_names << "formtastic" + class_names << case record_or_name_or_array + when String, Symbol then record_or_name_or_array.to_s # :post => "post" + when Array then record_or_name_or_array.last.class.to_s.underscore # [@post, @comment] # => "comment" + else record_or_name_or_array.class.to_s.underscore # @post => "post" + end + options[:html][:class] = class_names.join(" ") + + #{meth}(record_or_name_or_array, *(args << options), &proc) + end + END_SRC + module_eval src, __FILE__, __LINE__ + end + end +end diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/justin_french/formtastic.rb b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/justin_french/formtastic.rb new file mode 100644 index 000000000..74c01c8ac --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/justin_french/formtastic.rb @@ -0,0 +1,10 @@ +module JustinFrench + module Formtastic + class SemanticFormBuilder < ::Formtastic::SemanticFormBuilder + def initialize(*args) + ::ActiveSupport::Deprecation.warn("JustinFrench::Formtastic::SemanticFormBuilder is deprecated. User Formtastic::SemanticFormBuilder instead", caller) + super + end + end + end +end diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/locale/en.yml b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/locale/en.yml new file mode 100644 index 000000000..640e7f3db --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/lib/locale/en.yml @@ -0,0 +1,8 @@ +en: + formtastic: + yes: 'Yes' + no: 'No' + create: 'Create' + save: 'Save' + submit: 'Submit' + required: 'Required' diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/rails/init.rb b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/rails/init.rb new file mode 100644 index 000000000..cf8de6a71 --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/rails/init.rb @@ -0,0 +1,3 @@ +require File.join(File.dirname(__FILE__), *%w[.. lib formtastic]) +require File.join(File.dirname(__FILE__), *%w[.. lib justin_french formtastic]) +ActionView::Base.send :include, Formtastic::SemanticFormHelper diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/spec/formtastic_spec.rb b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/spec/formtastic_spec.rb new file mode 100644 index 000000000..be64c57da --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/spec/formtastic_spec.rb @@ -0,0 +1,2900 @@ +require File.dirname(__FILE__) + '/test_helper' +require 'formtastic' + +module FormtasticSpecHelper + def default_input_type(column_type, column_name = :generic_column_name) + @new_post.stub!(column_name) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => column_type)) unless column_type.nil? + + semantic_form_for(@new_post) do |builder| + @default_type = builder.send(:default_input_type, column_name) + end + + return @default_type + end +end + +describe 'Formtastic' do + + include ActionView::Helpers::FormHelper + include ActionView::Helpers::FormTagHelper + include ActionView::Helpers::FormOptionsHelper + include ActionView::Helpers::UrlHelper + include ActionView::Helpers::TagHelper + include ActionView::Helpers::TextHelper + include ActionView::Helpers::ActiveRecordHelper + include ActionView::Helpers::RecordIdentificationHelper + include ActionView::Helpers::DateHelper + include ActionView::Helpers::CaptureHelper + include ActiveSupport + include ActionController::PolymorphicRoutes + + include Formtastic::SemanticFormHelper + + attr_accessor :output_buffer + + def protect_against_forgery?; false; end + + before do + Formtastic::SemanticFormBuilder.label_str_method = :humanize + + @output_buffer = '' + + # Resource-oriented styles like form_for(@post) will expect a path method for the object, + # so we're defining some here. + def post_path(o); "/posts/1"; end + def posts_path; "/posts"; end + def new_post_path; "/posts/new"; end + + def author_path(o); "/authors/1"; end + def authors_path; "/authors"; end + def new_author_path; "/authors/new"; end + + # Sometimes we need some classes + class Post; + def id; end + end + class Author; end + + @fred = mock('user') + @fred.stub!(:class).and_return(Author) + @fred.stub!(:to_label).and_return('Fred Smith') + @fred.stub!(:login).and_return('fred_smith') + @fred.stub!(:id).and_return(37) + @fred.stub!(:new_record?).and_return(false) + @fred.stub!(:errors).and_return(mock('errors', :on => nil)) + + @bob = mock('user') + @bob.stub!(:class).and_return(Author) + @bob.stub!(:to_label).and_return('Bob Rock') + @bob.stub!(:login).and_return('bob') + @bob.stub!(:id).and_return(42) + @bob.stub!(:posts).and_return([]) + @bob.stub!(:post_ids).and_return([]) + @bob.stub!(:new_record?).and_return(false) + @bob.stub!(:errors).and_return(mock('errors', :on => nil)) + + Author.stub!(:find).and_return([@fred, @bob]) + Author.stub!(:human_attribute_name).and_return { |column_name| column_name.humanize } + Author.stub!(:human_name).and_return('Author') + Author.stub!(:reflect_on_all_validations).and_return([]) + Author.stub!(:reflect_on_association).and_return { |column_name| mock('reflection', :klass => Post, :macro => :has_many) if column_name == :posts } + + # Sometimes we need a mock @post object and some Authors for belongs_to + @new_post = mock('post') + @new_post.stub!(:class).and_return(Post) + @new_post.stub!(:id).and_return(nil) + @new_post.stub!(:new_record?).and_return(true) + @new_post.stub!(:errors).and_return(mock('errors', :on => nil)) + @new_post.stub!(:author).and_return(nil) + + @freds_post = mock('post') + @freds_post.stub!(:class).and_return(Post) + @freds_post.stub!(:to_label).and_return('Fred Smith') + @freds_post.stub!(:id).and_return(19) + @freds_post.stub!(:author).and_return(@fred) + @freds_post.stub!(:author_id).and_return(@fred.id) + @freds_post.stub!(:authors).and_return([@fred]) + @freds_post.stub!(:author_ids).and_return([@fred.id]) + @freds_post.stub!(:new_record?).and_return(false) + @freds_post.stub!(:errors).and_return(mock('errors', :on => nil)) + @fred.stub!(:posts).and_return([@freds_post]) + @fred.stub!(:post_ids).and_return([@freds_post.id]) + + Post.stub!(:human_attribute_name).and_return { |column_name| column_name.humanize } + Post.stub!(:human_name).and_return('Post') + Post.stub!(:reflect_on_all_validations).and_return([]) + Post.stub!(:reflect_on_association).and_return do |column_name| + case column_name + when :author, :author_status + mock('reflection', :klass => Author, :macro => :belongs_to) + when :authors + mock('reflection', :klass => Author, :macro => :has_and_belongs_to_many) + end + end + Post.stub!(:find).and_return([@freds_post]) + end + + describe 'JustinFrench::Formtastic::SemanticFormBuilder' do + require 'justin_french/formtastic' + it 'should be deprecated' do + ::ActiveSupport::Deprecation.should_receive(:warn).with(/JustinFrench\:\:Formtastic\:\:SemanticFormBuilder/, anything()) + form_for(@new_post, :builder => JustinFrench::Formtastic::SemanticFormBuilder) do |builder| + end + end + end + + describe 'SemanticFormHelper' do + + describe '#semantic_form_for' do + + it 'yields an instance of SemanticFormBuilder' do + semantic_form_for(:post, Post.new, :url => '/hello') do |builder| + builder.class.should == Formtastic::SemanticFormBuilder + end + end + + it 'adds a class of "formtastic" to the generated form' do + semantic_form_for(:post, Post.new, :url => '/hello') do |builder| + end + output_buffer.should have_tag("form.formtastic") + end + + it 'adds class matching the object name to the generated form when a symbol is provided' do + semantic_form_for(:post, Post.new, :url => '/hello') do |builder| + end + output_buffer.should have_tag("form.post") + + semantic_form_for(:project, :url => '/hello') do |builder| + end + output_buffer.should have_tag("form.project") + end + + it 'adds class matching the object\'s class to the generated form when an object is provided' do + semantic_form_for(@new_post) do |builder| + end + output_buffer.should have_tag("form.post") + end + + describe 'allows :html options' do + before(:each) do + semantic_form_for(:post, Post.new, :url => '/hello', :html => { :id => "something-special", :class => "something-extra", :multipart => true }) do |builder| + end + end + + it 'to add a id of "something-special" to generated form' do + output_buffer.should have_tag("form#something-special") + end + + it 'to add a class of "something-extra" to generated form' do + output_buffer.should have_tag("form.something-extra") + end + + it 'to add enctype="multipart/form-data"' do + output_buffer.should have_tag('form[@enctype="multipart/form-data"]') + end + end + + it 'can be called with a resource-oriented style' do + semantic_form_for(@new_post) do |builder| + builder.object.class.should == Post + builder.object_name.should == "post" + end + end + + it 'can be called with a generic style and instance variable' do + semantic_form_for(:post, @new_post, :url => new_post_path) do |builder| + builder.object.class.should == Post + builder.object_name.to_s.should == "post" # TODO: is this forced .to_s a bad assumption somewhere? + end + end + + it 'can be called with a generic style and inline object' do + semantic_form_for(:post, Post.new, :url => new_post_path) do |builder| + builder.object.class.should == Post + builder.object_name.to_s.should == "post" # TODO: is this forced .to_s a bad assumption somewhere? + end + end + + end + + describe '#semantic_fields_for' do + it 'yields an instance of SemanticFormBuilder' do + semantic_fields_for(:post, Post.new, :url => '/hello') do |builder| + builder.class.should == Formtastic::SemanticFormBuilder + end + end + end + + describe '#semantic_form_remote_for' do + it 'yields an instance of SemanticFormBuilder' do + semantic_form_remote_for(:post, Post.new, :url => '/hello') do |builder| + builder.class.should == Formtastic::SemanticFormBuilder + end + end + end + + describe '#semantic_form_for_remote' do + it 'yields an instance of SemanticFormBuilder' do + semantic_form_remote_for(:post, Post.new, :url => '/hello') do |builder| + builder.class.should == Formtastic::SemanticFormBuilder + end + end + end + + end + + describe 'SemanticFormBuilder' do + + include FormtasticSpecHelper + + describe "@@builder" do + before do + @new_post.stub!(:title) + @new_post.stub!(:body) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255)) + end + + after do + Formtastic::SemanticFormHelper.builder = Formtastic::SemanticFormBuilder + end + + it "can be overridden" do + + class CustomFormBuilder < Formtastic::SemanticFormBuilder + def custom(arg1, arg2, options = {}) + [arg1, arg2, options] + end + end + + Formtastic::SemanticFormHelper.builder = CustomFormBuilder + + semantic_form_for(@new_post) do |builder| + builder.class.should == CustomFormBuilder + builder.custom("one", "two").should == ["one", "two", {}] + end + end + + end + + describe 'Formtastic::SemanticFormBuilder#semantic_fields_for' do + before do + @new_post.stub!(:author).and_return(Author.new) + end + + it 'yields an instance of SemanticFormBuilder' do + semantic_form_for(@new_post) do |builder| + builder.semantic_fields_for(:author) do |nested_builder| + nested_builder.class.should == Formtastic::SemanticFormBuilder + end + end + end + + it 'nests the object name' do + semantic_form_for(@new_post) do |builder| + builder.semantic_fields_for(@bob) do |nested_builder| + nested_builder.object_name.should == 'post[author]' + end + end + end + + it 'should sanitize html id for li tag' do + @bob.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255)) + semantic_form_for(@new_post) do |builder| + builder.semantic_fields_for(@bob, :index => 1) do |nested_builder| + concat(nested_builder.inputs(:login)) + end + end + output_buffer.should have_tag('form fieldset.inputs #post_author_1_login_input') + output_buffer.should_not have_tag('form fieldset.inputs #post[author]_1_login_input') + end + end + + describe '#label' do + it 'should humanize the given attribute' do + semantic_form_for(@new_post) do |builder| + builder.label(:login).should have_tag('label', :with => /Login/) + end + end + + it 'should be printed as span' do + semantic_form_for(@new_post) do |builder| + builder.label(:login, nil, { :required => true, :as_span => true }).should have_tag('span.label abbr') + end + end + + describe 'when required is given' do + it 'should append a required note' do + semantic_form_for(@new_post) do |builder| + builder.label(:login, nil, :required => true).should have_tag('label abbr') + end + end + + it 'should allow require option to be given as second argument' do + semantic_form_for(@new_post) do |builder| + builder.label(:login, :required => true).should have_tag('label abbr') + end + end + end + + describe 'when label is given' do + it 'should allow the text to be given as label option' do + semantic_form_for(@new_post) do |builder| + builder.label(:login, :required => true, :label => 'My label').should have_tag('label', :with => /My label/) + end + end + + it 'should return nil if label is false' do + semantic_form_for(@new_post) do |builder| + builder.label(:login, :label => false).should be_nil + end + end + end + end + + describe '#errors_on' do + before(:each) do + @title_errors = ['must not be blank', 'must be longer than 10 characters', 'must be awesome'] + @errors = mock('errors') + @errors.stub!(:on).with('title').and_return(@title_errors) + @errors.stub!(:on).with('body').and_return(nil) + @new_post.stub!(:errors).and_return(@errors) + end + + describe 'and the errors will be displayed as a sentence' do + it 'should render a paragraph with the errors joined into a sentence' do + Formtastic::SemanticFormBuilder.inline_errors = :sentence + semantic_form_for(@new_post) do |builder| + builder.errors_on(:title).should have_tag('p.inline-errors', @title_errors.to_sentence) + end + end + end + + describe 'and the errors will be displayed as a list' do + it 'should render an unordered list with the class errors' do + Formtastic::SemanticFormBuilder.inline_errors = :list + semantic_form_for(@new_post) do |builder| + builder.errors_on(:title).should have_tag('ul.errors') + end + end + + it 'should include a list element for each of the errors within the unordered list' do + Formtastic::SemanticFormBuilder.inline_errors = :list + semantic_form_for(@new_post) do |builder| + @title_errors.each do |error| + builder.errors_on(:title).should have_tag('ul.errors li', error) + end + end + end + end + + describe 'but the errors will not be shown' do + it 'should return nil' do + Formtastic::SemanticFormBuilder.inline_errors = :none + semantic_form_for(@new_post) do |builder| + builder.errors_on(:title).should be_nil + end + end + end + + describe 'and no error is found on the method' do + it 'should return nil' do + Formtastic::SemanticFormBuilder.inline_errors = :sentence + semantic_form_for(@new_post) do |builder| + builder.errors_on(:body).should be_nil + end + end + end + end + + describe '#input' do + + before do + @new_post.stub!(:title) + @new_post.stub!(:body) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255)) + end + + describe 'with inline order customization' do + it 'should allow input, hints, errors as order' do + Formtastic::SemanticFormBuilder.inline_order = [:input, :hints, :errors] + + semantic_form_for(@new_post) do |builder| + builder.should_receive(:inline_input_for).once.ordered + builder.should_receive(:inline_hints_for).once.ordered + builder.should_receive(:inline_errors_for).once.ordered + concat(builder.input(:title)) + end + end + + it 'should allow hints, input, errors as order' do + Formtastic::SemanticFormBuilder.inline_order = [:hints, :input, :errors] + + semantic_form_for(@new_post) do |builder| + builder.should_receive(:inline_hints_for).once.ordered + builder.should_receive(:inline_input_for).once.ordered + builder.should_receive(:inline_errors_for).once.ordered + concat(builder.input(:title)) + end + end + end + + describe 'arguments and options' do + + it 'should require the first argument (the method on form\'s object)' do + lambda { + semantic_form_for(@new_post) do |builder| + concat(builder.input()) # no args passed in at all + end + }.should raise_error(ArgumentError) + end + + describe ':required option' do + + describe 'when true' do + + before do + @string = Formtastic::SemanticFormBuilder.required_string = " required yo!" # ensure there's something in the string + @new_post.class.should_not_receive(:reflect_on_all_validations) + end + + after do + Formtastic::SemanticFormBuilder.required_string = %{*} + end + + it 'should set a "required" class' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :required => true)) + end + output_buffer.should_not have_tag('form li.optional') + output_buffer.should have_tag('form li.required') + end + + it 'should append the "required" string to the label' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :required => true)) + end + output_buffer.should have_tag('form li.required label', /#{@string}$/) + end + + end + + describe 'when false' do + + before do + @string = Formtastic::SemanticFormBuilder.optional_string = " optional yo!" # ensure there's something in the string + @new_post.class.should_not_receive(:reflect_on_all_validations) + end + + after do + Formtastic::SemanticFormBuilder.optional_string = '' + end + + it 'should set an "optional" class' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :required => false)) + end + output_buffer.should_not have_tag('form li.required') + output_buffer.should have_tag('form li.optional') + end + + it 'should append the "optional" string to the label' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :required => false)) + end + output_buffer.should have_tag('form li.optional label', /#{@string}$/) + end + + end + + describe 'when not provided' do + + describe 'and an object was not given' do + + it 'should use the default value' do + Formtastic::SemanticFormBuilder.all_fields_required_by_default.should == true + Formtastic::SemanticFormBuilder.all_fields_required_by_default = false + + semantic_form_for(:project, :url => 'http://test.host/') do |builder| + concat(builder.input(:title)) + end + output_buffer.should_not have_tag('form li.required') + output_buffer.should have_tag('form li.optional') + + Formtastic::SemanticFormBuilder.all_fields_required_by_default = true + end + + end + + describe 'and an object was given' do + + describe 'and the validation reflection plugin is available' do + + before do + @new_post.class.stub!(:method_defined?).with(:reflect_on_all_validations).and_return(true) + end + + describe 'and validates_presence_of was called for the method' do + before do + @new_post.class.should_receive(:reflect_on_all_validations).and_return([ + mock('MacroReflection', :macro => :validates_presence_of, :name => :title) + ]) + end + + it 'should be required' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should have_tag('form li.required') + output_buffer.should_not have_tag('form li.optional') + end + end + + describe 'and validates_presence_of was not called for the method' do + before do + @new_post.class.should_receive(:reflect_on_all_validations).and_return([]) + end + + it 'should not be required' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should_not have_tag('form li.required') + output_buffer.should have_tag('form li.optional') + end + end + + end + + describe 'and the validation reflection plugin is not available' do + + it 'should use the default value' do + Formtastic::SemanticFormBuilder.all_fields_required_by_default.should == true + Formtastic::SemanticFormBuilder.all_fields_required_by_default = false + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should_not have_tag('form li.required') + output_buffer.should have_tag('form li.optional') + + Formtastic::SemanticFormBuilder.all_fields_required_by_default = true + end + + end + + end + + end + + end + + describe ':as option' do + + describe 'when not provided' do + + it 'should default to a string for forms without objects' do + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.input(:anything)) + end + output_buffer.should have_tag('form li.string') + end + + it 'should default to a string for methods on objects that don\'t respond to "column_for_attribute"' do + @new_post.stub!(:method_without_a_database_column) + @new_post.stub!(:column_for_attribute).and_return(nil) + default_input_type(nil, :method_without_a_database_column).should == :string + end + + it 'should default to :password for methods that don\'t have a column in the database but "password" is in the method name' do + @new_post.stub!(:password_method_without_a_database_column) + @new_post.stub!(:column_for_attribute).and_return(nil) + default_input_type(nil, :password_method_without_a_database_column).should == :password + end + + it 'should default to :password for methods on objects that don\'t respond to "column_for_attribute" but "password" is in the method name' do + @new_post.stub!(:password_method_without_a_database_column) + @new_post.stub!(:column_for_attribute).and_return(nil) + default_input_type(nil, :password_method_without_a_database_column).should == :password + end + + it 'should default to :select for column names ending in "_id"' do + default_input_type(:integer, :user_id).should == :select + default_input_type(:integer, :section_id).should == :select + end + + it 'should default to :password for :string column types with "password" in the method name' do + default_input_type(:string, :password).should == :password + default_input_type(:string, :hashed_password).should == :password + default_input_type(:string, :password_hash).should == :password + end + + it 'should default to :text for :text column types' do + default_input_type(:text).should == :text + end + + it 'should default to :date for :date column types' do + default_input_type(:date).should == :date + end + + it 'should default to :datetime for :datetime and :timestamp column types' do + default_input_type(:datetime).should == :datetime + default_input_type(:timestamp).should == :datetime + end + + it 'should default to :time for :time column types' do + default_input_type(:time).should == :time + end + + it 'should default to :boolean for :boolean column types' do + default_input_type(:boolean).should == :boolean + end + + it 'should default to :string for :string column types' do + default_input_type(:string).should == :string + end + + it 'should default to :numeric for :integer, :float and :decimal column types' do + default_input_type(:integer).should == :numeric + default_input_type(:float).should == :numeric + default_input_type(:decimal).should == :numeric + end + + it 'should default to :country for :string columns named country' do + default_input_type(:string, :country).should == :country + end + + describe 'defaulting to file column' do + Formtastic::SemanticFormBuilder.file_methods.each do |method| + it "should default to :file for attributes that respond to ##{method}" do + @new_post.stub!(:column_for_attribute).and_return(nil) + column = mock('column') + + Formtastic::SemanticFormBuilder.file_methods.each do |test| + column.stub!(:respond_to?).with(test).and_return(method == test) + end + + @new_post.should_receive(method).and_return(column) + + semantic_form_for(@new_post) do |builder| + builder.send(:default_input_type, method).should == :file + end + end + end + + end + end + + it 'should call the corresponding input method' do + [:select, :time_zone, :radio, :date, :datetime, :time, :boolean, :check_boxes, :hidden].each do |input_style| + @new_post.stub!(:generic_column_name) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255)) + semantic_form_for(@new_post) do |builder| + builder.should_receive(:"#{input_style}_input").once.and_return("fake HTML output from #input") + concat(builder.input(:generic_column_name, :as => input_style)) + end + end + + Formtastic::SemanticFormBuilder::INPUT_MAPPINGS.keys.each do |input_style| + @new_post.stub!(:generic_column_name) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255)) + semantic_form_for(@new_post) do |builder| + builder.should_receive(:input_simple).once.and_return("fake HTML output from #input") + concat(builder.input(:generic_column_name, :as => input_style)) + end + end + end + + end + + describe ':label option' do + + describe 'when provided' do + + it 'should be passed down to the label tag' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :label => "Kustom")) + end + output_buffer.should have_tag("form li label", /Kustom/) + end + + end + + describe 'when not provided' do + describe 'and object is not given' do + it 'should default the humanized method name, passing it down to the label tag' do + Formtastic::SemanticFormBuilder.label_str_method = :humanize + + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.input(:meta_description)) + end + + output_buffer.should have_tag("form li label", /#{'meta_description'.humanize}/) + end + end + + describe 'and object is given' do + it 'should delegate the label logic to class human attribute name and pass it down to the label tag' do + @new_post.stub!(:meta_description) # a two word method name + @new_post.class.should_receive(:human_attribute_name).with('meta_description').and_return('meta_description'.humanize) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:meta_description)) + end + + output_buffer.should have_tag("form li label", /#{'meta_description'.humanize}/) + end + end + end + + end + + describe ':hint option' do + + describe 'when provided' do + it 'should be passed down to the paragraph tag' do + hint_text = "this is the title of the post" + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :hint => hint_text)) + end + output_buffer.should have_tag("form li p.inline-hints", hint_text) + end + end + + describe 'when not provided' do + it 'should not render a hint paragraph' do + hint_text = "this is the title of the post" + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should_not have_tag("form li p.inline-hints") + end + end + + end + + describe ':wrapper_html option' do + + describe 'when provided' do + it 'should be passed down to the li tag' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :wrapper_html => {:id => :another_id})) + end + output_buffer.should have_tag("form li#another_id") + end + + it 'should append given classes to li default classes' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :wrapper_html => {:class => :another_class}, :required => true)) + end + output_buffer.should have_tag("form li.string") + output_buffer.should have_tag("form li.required") + output_buffer.should have_tag("form li.another_class") + end + + it 'should allow classes to be an array' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :wrapper_html => {:class => [ :my_class, :another_class ]})) + end + output_buffer.should have_tag("form li.string") + output_buffer.should have_tag("form li.my_class") + output_buffer.should have_tag("form li.another_class") + end + end + + describe 'when not provided' do + it 'should use default id and class' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should have_tag("form li#post_title_input") + output_buffer.should have_tag("form li.string") + end + end + + end + end + + describe ':as any type of input' do + + it 'should create a list item for each input' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + concat(builder.input(:body)) + end + output_buffer.should have_tag('form li', :count => 2) + end + + describe 'when there are errors on the object for this method' do + before do + @title_errors = ['must not be blank', 'must be longer than 10 characters', 'must be awesome'] + @errors = mock('errors') + @errors.stub!(:on).with('title').and_return(@title_errors) + @new_post.stub!(:errors).and_return(@errors) + end + + it 'should apply an errors class to the list item' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should have_tag('form li.error') + end + + it 'should not wrap the input with the Rails default error wrapping' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should_not have_tag('div.fieldWithErrors') + end + + it 'should render a paragraph for the errors' do + Formtastic::SemanticFormBuilder.inline_errors = :sentence + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should have_tag('form li.error p.inline-errors') + end + + it 'should not display an error list' do + Formtastic::SemanticFormBuilder.inline_errors = :list + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + output_buffer.should have_tag('form li.error ul.errors') + end + end + + describe 'when there are no errors on the object for this method' do + before do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title)) + end + end + + it 'should not apply an errors class to the list item' do + output_buffer.should_not have_tag('form li.error') + end + + it 'should not render a paragraph for the errors' do + output_buffer.should_not have_tag('form li.error p.inline-errors') + end + + it 'should not display an error list' do + output_buffer.should_not have_tag('form li.error ul.errors') + end + end + + describe 'when no object is provided' do + before do + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.input(:title)) + end + end + + it 'should not apply an errors class to the list item' do + output_buffer.should_not have_tag('form li.error') + end + + it 'should not render a paragraph for the errors' do + output_buffer.should_not have_tag('form li.error p.inline-errors') + end + + it 'should not display an error list' do + output_buffer.should_not have_tag('form li.error ul.errors') + end + end + end + + # Test string_mappings: :string, :password and :numeric + string_mappings = Formtastic::SemanticFormBuilder::INPUT_MAPPINGS.slice(*Formtastic::SemanticFormBuilder::STRING_MAPPINGS) + string_mappings.each do |type, template_method| + describe ":as => #{type.inspect}" do + + before do + @new_post.stub!(:title) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => type, :limit => 50)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :as => type)) + end + end + + it "should have a #{type} class on the wrapper" do + output_buffer.should have_tag("form li.#{type}") + end + + it 'should have a post_title_input id on the wrapper' do + output_buffer.should have_tag('form li#post_title_input') + end + + it 'should generate a label for the input' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label[@for="post_title"') + output_buffer.should have_tag('form li label', /Title/) + end + + input_type = template_method.to_s.split('_').first + + it "should generate a #{input_type} input" do + output_buffer.should have_tag("form li input") + output_buffer.should have_tag("form li input#post_title") + output_buffer.should have_tag("form li input[@type=\"#{input_type}\"]") + output_buffer.should have_tag("form li input[@name=\"post[title]\"]") + end + + it 'should have a maxlength matching the column limit' do + @new_post.column_for_attribute(:title).limit.should == 50 + output_buffer.should have_tag("form li input[@maxlength='50']") + end + + it 'should use default_text_field_size for columns longer than default_text_field_size' do + default_size = Formtastic::SemanticFormBuilder.default_text_field_size + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => type, :limit => default_size * 2)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :as => type)) + end + + output_buffer.should have_tag("form li input[@size='#{default_size}']") + end + + it 'should use the column size for columns shorter than default_text_field_size' do + column_limit_shorted_than_default = 1 + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => type, :limit => column_limit_shorted_than_default)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :as => type)) + end + + output_buffer.should have_tag("form li input[@size='#{column_limit_shorted_than_default}']") + end + + it 'should use default_text_field_size for methods without database columns' do + default_size = Formtastic::SemanticFormBuilder.default_text_field_size + @new_post.stub!(:column_for_attribute).and_return(nil) # Return a nil column + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :as => type)) + end + + output_buffer.should have_tag("form li input[@size='#{default_size}']") + end + + it 'should use input_html to style inputs' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :as => type, :input_html => { :class => 'myclass' })) + end + output_buffer.should have_tag("form li input.myclass") + end + + it 'should generate input and labels even if no object is given' do + semantic_form_for(:project, :url => 'http://test.host/') do |builder| + concat(builder.input(:title, :as => type)) + end + + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label[@for="project_title"') + output_buffer.should have_tag('form li label', /Title/) + + output_buffer.should have_tag("form li input") + output_buffer.should have_tag("form li input#project_title") + output_buffer.should have_tag("form li input[@type=\"#{input_type}\"]") + output_buffer.should have_tag("form li input[@name=\"project[title]\"]") + end + + end + end + + # Test other mappings that are not strings: :text and :file. + other_mappings = Formtastic::SemanticFormBuilder::INPUT_MAPPINGS.except(*Formtastic::SemanticFormBuilder::STRING_MAPPINGS) + other_mappings.each do |type, template_method| + describe ":as => #{type.inspect}" do + + before do + @new_post.stub!(:body) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => type)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:body, :as => type)) + end + end + + it "should have a #{type} class on the wrapper" do + output_buffer.should have_tag('form li.#{type}') + end + + it 'should have a post_title_input id on the wrapper' do + output_buffer.should have_tag('form li#post_body_input') + end + + it 'should generate a label for the input' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label[@for="post_body"') + output_buffer.should have_tag('form li label', /Body/) + end + + input_type = template_method.to_s.gsub(/_field|_/, '') + + if template_method.to_s =~ /_field$/ # password_field + + it "should generate a #{input_type} input" do + output_buffer.should have_tag("form li input") + output_buffer.should have_tag("form li input#post_body") + output_buffer.should have_tag("form li input[@name=\"post[body]\"]") + output_buffer.should have_tag("form li input[@type=\"#{input_type}\"]") + end + + it 'should use input_html to style inputs' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :as => type, :input_html => { :class => 'myclass' })) + end + output_buffer.should have_tag("form li input.myclass") + end + + else # text_area + + it "should generate a #{input_type} input" do + output_buffer.should have_tag("form li #{input_type}") + output_buffer.should have_tag("form li #{input_type}#post_body") + output_buffer.should have_tag("form li #{input_type}[@name=\"post[body]\"]") + end + + it 'should use input_html to style inputs' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:title, :as => type, :input_html => { :class => 'myclass' })) + end + output_buffer.should have_tag("form li #{input_type}.myclass") + end + + end + + describe 'when no object is given' do + before(:each) do + semantic_form_for(:project, :url => 'http://test.host/') do |builder| + concat(builder.input(:title, :as => type)) + end + end + + it 'should generate input' do + if template_method.to_s =~ /_field$/ # password_field + output_buffer.should have_tag("form li input") + output_buffer.should have_tag("form li input#project_title") + output_buffer.should have_tag("form li input[@type=\"#{input_type}\"]") + output_buffer.should have_tag("form li input[@name=\"project[title]\"]") + else + output_buffer.should have_tag("form li #{input_type}") + output_buffer.should have_tag("form li #{input_type}#project_title") + output_buffer.should have_tag("form li #{input_type}[@name=\"project[title]\"]") + end + end + + it 'should generate labels' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label[@for="project_title"') + output_buffer.should have_tag('form li label', /Title/) + end + end + + end + end + + describe ":as => :hidden" do + before do + @new_post.stub!(:hidden) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:hidden, :as => :hidden)) + end + end + + it "should have a hidden class on the wrapper" do + output_buffer.should have_tag('form li.hidden') + end + + it 'should have a post_hidden_input id on the wrapper' do + output_buffer.should have_tag('form li#post_hidden_input') + end + + it 'should not generate a label for the input' do + output_buffer.should_not have_tag('form li label') + end + + it "should generate a input field" do + output_buffer.should have_tag("form li input#post_hidden") + output_buffer.should have_tag("form li input[@type=\"hidden\"]") + output_buffer.should have_tag("form li input[@name=\"post[hidden]\"]") + end + end + + describe ":as => :time_zone" do + before do + @new_post.stub!(:time_zone) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:time_zone)) + end + end + + it "should have a time_zone class on the wrapper" do + output_buffer.should have_tag('form li.time_zone') + end + + it 'should have a post_title_input id on the wrapper' do + output_buffer.should have_tag('form li#post_time_zone_input') + end + + it 'should generate a label for the input' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label[@for="post_time_zone"') + output_buffer.should have_tag('form li label', /Time zone/) + end + + it "should generate a select" do + output_buffer.should have_tag("form li select") + output_buffer.should have_tag("form li select#post_time_zone") + output_buffer.should have_tag("form li select[@name=\"post[time_zone]\"]") + end + + it 'should use input_html to style inputs' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:time_zone, :input_html => { :class => 'myclass' })) + end + output_buffer.should have_tag("form li select.myclass") + end + + describe 'when no object is given' do + before(:each) do + semantic_form_for(:project, :url => 'http://test.host/') do |builder| + concat(builder.input(:time_zone, :as => :time_zone)) + end + end + + it 'should generate labels' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label[@for="project_time_zone"') + output_buffer.should have_tag('form li label', /Time zone/) + end + + it 'should generate select inputs' do + output_buffer.should have_tag("form li select") + output_buffer.should have_tag("form li select#project_time_zone") + output_buffer.should have_tag("form li select[@name=\"project[time_zone]\"]") + end + end + end + + describe ":as => :country" do + + before do + @new_post.stub!(:country) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string)) + end + + describe "when country_select is not available as a helper from a plugin" do + + it "should raise an error, sugesting the author installs a plugin" do + lambda { + semantic_form_for(@new_post) do |builder| + concat(builder.input(:country, :as => :country)) + end + }.should raise_error + end + + end + + describe "when country_select is available as a helper (from a plugin)" do + + before do + semantic_form_for(@new_post) do |builder| + builder.stub!(:country_select).and_return("") + concat(builder.input(:country, :as => :country)) + end + end + + it "should have a time_zone class on the wrapper" do + output_buffer.should have_tag('form li.country') + end + + it 'should have a post_title_input id on the wrapper' do + output_buffer.should have_tag('form li#post_country_input') + end + + it 'should generate a label for the input' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label[@for="post_country"') + output_buffer.should have_tag('form li label', /Country/) + end + + it "should generate a select" do + output_buffer.should have_tag("form li select") + end + + end + + describe ":priority_countries option" do + + it "should be passed down to the country_select helper when provided" do + priority_countries = ["Foo", "Bah"] + semantic_form_for(@new_post) do |builder| + builder.stub!(:country_select).and_return("") + builder.should_receive(:country_select).with(:country, priority_countries, {}, {}).and_return("") + + concat(builder.input(:country, :as => :country, :priority_countries => priority_countries)) + end + end + + it "should default to the @@priority_countries config when absent" do + priority_countries = Formtastic::SemanticFormBuilder.priority_countries + priority_countries.should_not be_empty + priority_countries.should_not be_nil + + semantic_form_for(@new_post) do |builder| + builder.stub!(:country_select).and_return("") + builder.should_receive(:country_select).with(:country, priority_countries, {}, {}).and_return("") + + concat(builder.input(:country, :as => :country)) + end + end + + end + + end + + describe ':as => :radio' do + + before do + @new_post.stub!(:author).and_return(@bob) + @new_post.stub!(:author_id).and_return(@bob.id) + Post.stub!(:reflect_on_association).and_return { |column_name| mock('reflection', :klass => Author, :macro => :belongs_to) } + end + + describe 'for belongs_to association' do + before do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => :radio, :value_as_class => true)) + end + end + + it 'should have a radio class on the wrapper' do + output_buffer.should have_tag('form li.radio') + end + + it 'should have a post_author_input id on the wrapper' do + output_buffer.should have_tag('form li#post_author_input') + end + + it 'should generate a fieldset and legend containing label text for the input' do + output_buffer.should have_tag('form li fieldset') + output_buffer.should have_tag('form li fieldset legend') + output_buffer.should have_tag('form li fieldset legend', /Author/) + end + + it 'should generate an ordered list with a list item for each choice' do + output_buffer.should have_tag('form li fieldset ol') + output_buffer.should have_tag('form li fieldset ol li', :count => Author.find(:all).size) + end + + it 'should have one option with a "checked" attribute' do + output_buffer.should have_tag('form li input[@checked]', :count => 1) + end + + describe "each choice" do + + it 'should contain a label for the radio input with a nested input and label text' do + Author.find(:all).each do |author| + output_buffer.should have_tag('form li fieldset ol li label', /#{author.to_label}/) + output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_id_#{author.id}']") + end + end + + it 'should use values as li.class when value_as_class is true' do + Author.find(:all).each do |author| + output_buffer.should have_tag("form li fieldset ol li.#{author.id} label") + end + end + + it "should have a radio input" do + Author.find(:all).each do |author| + output_buffer.should have_tag("form li fieldset ol li label input#post_author_id_#{author.id}") + output_buffer.should have_tag("form li fieldset ol li label input[@type='radio']") + output_buffer.should have_tag("form li fieldset ol li label input[@value='#{author.id}']") + output_buffer.should have_tag("form li fieldset ol li label input[@name='post[author_id]']") + end + end + + it "should mark input as checked if it's the the existing choice" do + @new_post.author_id.should == @bob.id + @new_post.author.id.should == @bob.id + @new_post.author.should == @bob + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => :radio)) + end + + output_buffer.should have_tag("form li fieldset ol li label input[@checked='checked']") + end + end + + describe 'and no object is given' do + before(:each) do + output_buffer.replace '' + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.input(:author_id, :as => :radio, :collection => Author.find(:all))) + end + end + + it 'should generate a fieldset with legend' do + output_buffer.should have_tag('form li fieldset legend', /Author/) + end + + it 'shold generate an li tag for each item in the collection' do + output_buffer.should have_tag('form li fieldset ol li', :count => Author.find(:all).size) + end + + it 'should generate labels for each item' do + Author.find(:all).each do |author| + output_buffer.should have_tag('form li fieldset ol li label', /#{author.to_label}/) + output_buffer.should have_tag("form li fieldset ol li label[@for='project_author_id_#{author.id}']") + end + end + + it 'should generate inputs for each item' do + Author.find(:all).each do |author| + output_buffer.should have_tag("form li fieldset ol li label input#project_author_id_#{author.id}") + output_buffer.should have_tag("form li fieldset ol li label input[@type='radio']") + output_buffer.should have_tag("form li fieldset ol li label input[@value='#{author.id}']") + output_buffer.should have_tag("form li fieldset ol li label input[@name='project[author_id]']") + end + end + end + end + end + + describe ':as => :select' do + + before do + @new_post.stub!(:author).and_return(@bob) + @new_post.stub!(:author_id).and_return(@bob.id) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :integer, :limit => 255)) + end + + describe 'for a belongs_to association' do + before do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => :select)) + end + end + + it 'should have a select class on the wrapper' do + output_buffer.should have_tag('form li.select') + end + + it 'should have a post_author_input id on the wrapper' do + output_buffer.should have_tag('form li#post_author_input') + end + + it 'should have a label inside the wrapper' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label', /Author/) + output_buffer.should have_tag("form li label[@for='post_author_id']") + end + + it 'should have a select inside the wrapper' do + output_buffer.should have_tag('form li select') + output_buffer.should have_tag('form li select#post_author_id') + end + + it 'should not create a multi-select' do + output_buffer.should_not have_tag('form li select[@multiple]') + end + + it 'should create a select without size' do + output_buffer.should_not have_tag('form li select[@size]') + end + + it 'should have a select option for each Author' do + output_buffer.should have_tag('form li select option', :count => Author.find(:all).size + 1) + Author.find(:all).each do |author| + output_buffer.should have_tag("form li select option[@value='#{author.id}']", /#{author.to_label}/) + end + end + + it 'should have one option with a "selected" attribute' do + output_buffer.should have_tag('form li select option[@selected]', :count => 1) + end + + it 'should not singularize the association name' do + @new_post.stub!(:author_status).and_return(@bob) + @new_post.stub!(:author_status_id).and_return(@bob.id) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :integer, :limit => 255)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author_status, :as => :select)) + end + + output_buffer.should have_tag('form li select#post_author_status_id') + end + end + + describe 'for a has_many association' do + before do + semantic_form_for(@fred) do |builder| + concat(builder.input(:posts, :as => :select)) + end + end + + it 'should have a select class on the wrapper' do + output_buffer.should have_tag('form li.select') + end + + it 'should have a post_author_input id on the wrapper' do + output_buffer.should have_tag('form li#author_posts_input') + end + + it 'should have a label inside the wrapper' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label', /Post ids/) + output_buffer.should have_tag("form li label[@for='author_post_ids']") + end + + it 'should have a select inside the wrapper' do + output_buffer.should have_tag('form li select') + output_buffer.should have_tag('form li select#author_post_ids') + end + + it 'should have a multi-select select' do + output_buffer.should have_tag('form li select[@multiple="multiple"]') + end + + it 'should have a select option for each Post' do + output_buffer.should have_tag('form li select option', :count => Post.find(:all).size + 1) + Post.find(:all).each do |post| + output_buffer.should have_tag("form li select option[@value='#{post.id}']", /#{post.to_label}/) + end + end + + it 'should have one option with a "selected" attribute' do + output_buffer.should have_tag('form li select option[@selected]', :count => 1) + end + end + + describe 'for a has_and_belongs_to_many association' do + before do + semantic_form_for(@freds_post) do |builder| + concat(builder.input(:authors, :as => :select)) + end + end + + it 'should have a select class on the wrapper' do + output_buffer.should have_tag('form li.select') + end + + it 'should have a post_author_input id on the wrapper' do + output_buffer.should have_tag('form li#post_authors_input') + end + + it 'should have a label inside the wrapper' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label', /Author ids/) + output_buffer.should have_tag("form li label[@for='post_author_ids']") + end + + it 'should have a select inside the wrapper' do + output_buffer.should have_tag('form li select') + output_buffer.should have_tag('form li select#post_author_ids') + end + + it 'should have a multi-select select' do + output_buffer.should have_tag('form li select[@multiple="multiple"]') + end + + it 'should have a select option for each Author' do + output_buffer.should have_tag('form li select option', :count => Author.find(:all).size + 1) + Author.find(:all).each do |author| + output_buffer.should have_tag("form li select option[@value='#{author.id}']", /#{author.to_label}/) + end + end + + it 'should have one option with a "selected" attribute' do + output_buffer.should have_tag('form li select option[@selected]', :count => 1) + end + end + + describe 'when :include_blank is not set' do + before do + @new_post.stub!(:author_id).and_return(nil) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => :select)) + end + end + + it 'should have a blank option by default' do + output_buffer.should have_tag("form li select option[@value='']", "") + end + end + + describe 'when :include_blank is set to false' do + before do + @new_post.stub!(:author_id).and_return(nil) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => :select, :include_blank => false)) + end + end + + it 'should not have a blank option' do + output_buffer.should_not have_tag("form li select option[@value='']", "") + end + end + + describe 'when :prompt => "choose something" is set' do + before do + @new_post.stub!(:author_id).and_return(nil) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => :select, :prompt => "choose author")) + end + end + + it 'should have a select with prompt' do + output_buffer.should have_tag("form li select option[@value='']", /choose author/) + end + + it 'should not have a blank select option' do + output_buffer.should_not have_tag("form li select option[@value='']", "") + end + end + + describe 'when no object is given' do + before(:each) do + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.input(:author, :as => :select, :collection => Author.find(:all))) + end + end + + it 'should generate label' do + output_buffer.should have_tag('form li label', /Author/) + output_buffer.should have_tag("form li label[@for='project_author']") + end + + it 'should generate select inputs' do + output_buffer.should have_tag('form li select#project_author') + output_buffer.should have_tag('form li select option', :count => Author.find(:all).size + 1) + end + + it 'should generate an option to each item' do + Author.find(:all).each do |author| + output_buffer.should have_tag("form li select option[@value='#{author.id}']", /#{author.to_label}/) + end + end + end + end + + describe ':as => :check_boxes' do + + describe 'for a has_many association' do + before do + semantic_form_for(@fred) do |builder| + concat(builder.input(:posts, :as => :check_boxes, :value_as_class => true)) + end + end + + it 'should have a check_boxes class on the wrapper' do + output_buffer.should have_tag('form li.check_boxes') + end + + it 'should have a author_posts_input id on the wrapper' do + output_buffer.should have_tag('form li#author_posts_input') + end + + it 'should generate a fieldset and legend containing label text for the input' do + output_buffer.should have_tag('form li fieldset') + output_buffer.should have_tag('form li fieldset legend') + output_buffer.should have_tag('form li fieldset legend', /Posts/) + end + + it 'should generate an ordered list with a list item for each choice' do + output_buffer.should have_tag('form li fieldset ol') + output_buffer.should have_tag('form li fieldset ol li', :count => Post.find(:all).size) + end + + it 'should have one option with a "checked" attribute' do + output_buffer.should have_tag('form li input[@checked]', :count => 1) + end + + it 'should generate hidden inputs with default value blank' do + output_buffer.should have_tag("form li fieldset ol li label input[@type='hidden'][@value='']", :count => Post.find(:all).size) + end + + describe "each choice" do + + it 'should contain a label for the radio input with a nested input and label text' do + Post.find(:all).each do |post| + output_buffer.should have_tag('form li fieldset ol li label', /#{post.to_label}/) + output_buffer.should have_tag("form li fieldset ol li label[@for='author_post_ids_#{post.id}']") + end + end + + it 'should use values as li.class when value_as_class is true' do + Post.find(:all).each do |post| + output_buffer.should have_tag("form li fieldset ol li.#{post.id} label") + end + end + + it 'should have a checkbox input for each post' do + Post.find(:all).each do |post| + output_buffer.should have_tag("form li fieldset ol li label input#author_post_ids_#{post.id}") + output_buffer.should have_tag("form li fieldset ol li label input[@name='author[post_ids][]']", :count => 2) + end + end + + it "should mark input as checked if it's the the existing choice" do + Post.find(:all).include?(@fred.posts.first).should be_true + output_buffer.should have_tag("form li fieldset ol li label input[@checked='checked']") + end + end + + describe 'and no object is given' do + before(:each) do + output_buffer.replace '' + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.input(:author_id, :as => :check_boxes, :collection => Author.find(:all))) + end + end + + it 'should generate a fieldset with legend' do + output_buffer.should have_tag('form li fieldset legend', /Author/) + end + + it 'shold generate an li tag for each item in the collection' do + output_buffer.should have_tag('form li fieldset ol li', :count => Author.find(:all).size) + end + + it 'should generate labels for each item' do + Author.find(:all).each do |author| + output_buffer.should have_tag('form li fieldset ol li label', /#{author.to_label}/) + output_buffer.should have_tag("form li fieldset ol li label[@for='project_author_id_#{author.id}']") + end + end + + it 'should generate inputs for each item' do + Author.find(:all).each do |author| + output_buffer.should have_tag("form li fieldset ol li label input#project_author_id_#{author.id}") + output_buffer.should have_tag("form li fieldset ol li label input[@type='checkbox']") + output_buffer.should have_tag("form li fieldset ol li label input[@value='#{author.id}']") + output_buffer.should have_tag("form li fieldset ol li label input[@name='project[author_id][]']") + end + end + end + end + end + + describe 'for collections' do + + before do + @new_post.stub!(:author).and_return(@bob) + @new_post.stub!(:author_id).and_return(@bob.id) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :integer, :limit => 255)) + end + + { :select => :option, :radio => :input, :check_boxes => :'input[@type="checkbox"]' }.each do |type, countable| + + describe ":as => #{type.inspect}" do + describe 'when the :collection option is not provided' do + it 'should perform a basic find on the association class' do + Author.should_receive(:find) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => type)) + end + end + + it 'should show a deprecation warning if user gives the association using _id' do + # Check for deprecation message + ::ActiveSupport::Deprecation.should_receive(:warn).with(/association/, anything()) + + Author.should_receive(:find) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author_id, :as => type)) + end + end + end + + describe 'when the :collection option is provided' do + + before do + @authors = Author.find(:all) * 2 + output_buffer.replace '' # clears the output_buffer from the before block, hax! + end + + it 'should not call find() on the parent class' do + Author.should_not_receive(:find) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => type, :collection => @authors)) + end + end + + it 'should use the provided collection' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => type, :collection => @authors)) + end + output_buffer.should have_tag("form li.#{type} #{countable}", :count => @authors.size + (type == :select ? 1 : 0)) + end + + describe 'and the :collection is an array of strings' do + before do + @new_post.stub!(:category_name).and_return('') + @categories = [ 'General', 'Design', 'Development' ] + end + + it "should use the string as the label text and value for each #{countable}" do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:category_name, :as => type, :collection => @categories)) + end + + @categories.each do |value| + output_buffer.should have_tag("form li.#{type}", /#{value}/) + output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value}']") + end + end + + if type == :radio + it 'should generate a sanitized label for attribute' do + @bob.stub!(:category_name).and_return(@categories) + semantic_form_for(@new_post) do |builder| + builder.semantic_fields_for(@bob) do |bob_builder| + concat(bob_builder.input(:category_name, :as => type, :collection => @categories)) + end + end + + @categories.each do |item| + output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_category_name_#{item.downcase}']") + end + end + end + end + + describe 'and the :collection is a hash of strings' do + before do + @new_post.stub!(:category_name).and_return('') + @categories = { 'General' => 'gen', 'Design' => 'des','Development' => 'dev' } + end + + it "should use the key as the label text and the hash value as the value attribute for each #{countable}" do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:category_name, :as => type, :collection => @categories)) + end + + @categories.each do |label, value| + output_buffer.should have_tag("form li.#{type}", /#{label}/) + output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value}']") + end + end + end + + describe 'and the :collection is an array of arrays' do + before do + @new_post.stub!(:category_name).and_return('') + @categories = { 'General' => 'gen', 'Design' => 'des','Development' => 'dev' }.to_a + end + + it "should use the first value as the label text and the last value as the value attribute for #{countable}" do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:category_name, :as => type, :collection => @categories)) + end + + @categories.each do |text, value| + label = type == :select ? :option : :label + output_buffer.should have_tag("form li.#{type} #{label}", /#{text}/i) + output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value.to_s}']") + end + end + end + + describe 'and the :collection is an array of symbols' do + before do + @new_post.stub!(:category_name).and_return('') + @categories = [ :General, :Design, :Development ] + end + + it "should use the symbol as the label text and value for each #{countable}" do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:category_name, :as => type, :collection => @categories)) + end + + @categories.each do |value| + label = type == :select ? :option : :label + output_buffer.should have_tag("form li.#{type} #{label}", /#{value}/i) + output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{value.to_s}']") + end + end + end + + describe 'when the :label_method option is provided' do + before do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => type, :label_method => :login)) + end + end + + it 'should have options with text content from the specified method' do + Author.find(:all).each do |author| + output_buffer.should have_tag("form li.#{type}", /#{author.login}/) + end + end + end + + describe 'when the :label_method option is not provided' do + Formtastic::SemanticFormBuilder.collection_label_methods.each do |label_method| + + describe "when the collection objects respond to #{label_method}" do + before do + @fred.stub!(:respond_to?).and_return { |m| m.to_s == label_method } + Author.find(:all).each { |a| a.stub!(label_method).and_return('The Label Text') } + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => type)) + end + end + + it "should render the options with #{label_method} as the label" do + Author.find(:all).each do |author| + output_buffer.should have_tag("form li.#{type}", /The Label Text/) + end + end + end + + end + end + + describe 'when the :value_method option is provided' do + before do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:author, :as => type, :value_method => :login)) + end + end + + it 'should have options with values from specified method' do + Author.find(:all).each do |author| + output_buffer.should have_tag("form li.#{type} #{countable}[@value='#{author.login}']") + end + end + end + + end + end + end + + describe 'for boolean attributes' do + + { :select => :option, :radio => :input }.each do |type, countable| + checked_or_selected = { :select => :selected, :radio => :checked }[type] + + describe ":as => #{type.inspect}" do + + before do + @new_post.stub!(:allow_comments) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => type)) + end + end + + it "should have a #{type} class on the wrapper" do + output_buffer.should have_tag("form li.#{type}") + end + + it 'should have a post_allow_comments_input id on the wrapper' do + output_buffer.should have_tag('form li#post_allow_comments_input') + end + + it 'should generate a fieldset containing a legend' do + output_buffer.should have_tag("form li.#{type}", /Allow comments/) + end + + it "should generate two #{countable}" do + output_buffer.should have_tag("form li.#{type} #{countable}", :count => (type == :select ? 3 : 2)) + output_buffer.should have_tag(%{form li.#{type} #{countable}[@value="true"]}) + output_buffer.should have_tag(%{form li.#{type} #{countable}[@value="false"]}) + end + + describe 'when the locale sets the label text' do + before do + I18n.backend.store_translations 'en', :formtastic => {:yes => 'Absolutely!', :no => 'Never!'} + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => type)) + end + end + + after do + I18n.backend.store_translations 'en', :formtastic => {:yes => nil, :no => nil} + end + + it 'should allow translation of the labels' do + output_buffer.should have_tag("form li.#{type}", /Absolutely\!/) + output_buffer.should have_tag("form li.#{type}", /Never\!/) + end + end + + describe 'when the value is nil' do + before do + @new_post.stub!(:allow_comments).and_return(nil) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => type)) + end + end + + it "should not mark either #{countable} as #{checked_or_selected}" do + output_buffer.should_not have_tag(%{form li.#{type} input[@#{checked_or_selected}="#{checked_or_selected}"]}) + end + end + + describe 'when the value is true' do + before do + @new_post.stub!(:allow_comments).and_return(true) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean)) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => type)) + end + end + + it "should mark the true #{countable} as #{checked_or_selected}" do + output_buffer.should have_tag(%{form li.#{type} #{countable}[@value="true"][@#{checked_or_selected}="#{checked_or_selected}"]}, :count => 1) + end + + it "should not mark the false #{countable} as #{checked_or_selected}" do + output_buffer.should_not have_tag(%{form li.#{type} #{countable}[@value="false"][@#{checked_or_selected}="#{checked_or_selected}"]}) + end + end + + describe 'when the value is false' do + before do + @new_post.stub!(:allow_comments).and_return(false) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean)) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => type)) + end + end + + it "should not mark the true #{countable} as #{checked_or_selected}" do + output_buffer.should_not have_tag(%{form li.#{type} #{countable}[@value="true"][@#{checked_or_selected}="#{checked_or_selected}"]}) + end + + it "should mark the false #{countable} as #{checked_or_selected}" do + output_buffer.should have_tag(%{form li.#{type} #{countable}[@value="false"][@#{checked_or_selected}="#{checked_or_selected}"]}, :count => 1) + end + end + + describe 'when :true and :false options are provided' do + before do + @new_post.stub!(:allow_comments) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean)) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => type, :true => "Absolutely", :false => "No Way")) + end + end + + it 'should use them as labels' do + output_buffer.should have_tag("form li.#{type}", /Absolutely/) + output_buffer.should have_tag("form li.#{type}", /No Way/) + end + end + end + + end + end + end + + describe ':as => :date' do + + before do + @new_post.stub!(:publish_at) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :date)) + + semantic_form_for(@new_post) do |@builder| + concat(@builder.input(:publish_at, :as => :date)) + end + end + + it 'should have a date class on the wrapper li' do + output_buffer.should have_tag('form li.date') + end + + it 'should have a fieldset inside the li wrapper' do + output_buffer.should have_tag('form li.date fieldset') + end + + it 'should have a legend containing the label text inside the fieldset' do + output_buffer.should have_tag('form li.date fieldset legend', /Publish at/) + end + + it 'should have an ordered list of three items inside the fieldset' do + output_buffer.should have_tag('form li.date fieldset ol') + output_buffer.should have_tag('form li.date fieldset ol li', :count => 3) + end + + it 'should have three labels for year, month and day' do + output_buffer.should have_tag('form li.date fieldset ol li label', :count => 3) + output_buffer.should have_tag('form li.date fieldset ol li label', /year/i) + output_buffer.should have_tag('form li.date fieldset ol li label', /month/i) + output_buffer.should have_tag('form li.date fieldset ol li label', /day/i) + end + + it 'should have three selects for year, month and day' do + output_buffer.should have_tag('form li.date fieldset ol li select', :count => 3) + end + end + + describe ':as => :datetime' do + + before do + @new_post.stub!(:publish_at) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :datetime)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:publish_at, :as => :datetime)) + end + end + + it 'should have a datetime class on the wrapper li' do + output_buffer.should have_tag('form li.datetime') + end + + it 'should have a fieldset inside the li wrapper' do + output_buffer.should have_tag('form li.datetime fieldset') + end + + it 'should have a legend containing the label text inside the fieldset' do + output_buffer.should have_tag('form li.datetime fieldset legend', /Publish at/) + end + + it 'should have an ordered list of five items inside the fieldset' do + output_buffer.should have_tag('form li.datetime fieldset ol') + output_buffer.should have_tag('form li.datetime fieldset ol li', :count => 5) + end + + it 'should have five labels for year, month, day, hour and minute' do + output_buffer.should have_tag('form li.datetime fieldset ol li label', :count => 5) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /year/i) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /month/i) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /day/i) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /hour/i) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /minute/i) + end + + it 'should have five selects for year, month, day, hour and minute' do + output_buffer.should have_tag('form li.datetime fieldset ol li select', :count => 5) + end + + it 'should generate a sanitized label and matching ids for attribute' do + @bob.stub!(:publish_at) + @bob.stub!(:column_for_attribute).and_return(mock('column', :type => :datetime)) + + semantic_form_for(@new_post) do |builder| + builder.semantic_fields_for(@bob, :index => 10) do |bob_builder| + concat(bob_builder.input(:publish_at, :as => :datetime)) + end + end + + 1.upto(5) do |i| + output_buffer.should have_tag("form li fieldset ol li label[@for='post_author_10_publish_at_#{i}i']") + output_buffer.should have_tag("form li fieldset ol li #post_author_10_publish_at_#{i}i") + end + end + + describe 'when :discard_input => true is set' do + it 'should use default hidden value equals to 1 when attribute returns nil' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:publish_at, :as => :datetime, :discard_day => true)) + end + + output_buffer.should have_tag("form li input[@type='hidden'][@value='1']") + end + + it 'should use default attribute value when it is not nil' do + @new_post.stub!(:publish_at).and_return(Date.new(2007,12,27)) + semantic_form_for(@new_post) do |builder| + concat(builder.input(:publish_at, :as => :datetime, :discard_day => true)) + end + + output_buffer.should have_tag("form li input[@type='hidden'][@value='27']") + end + end + + describe 'when :include_blank => true is set' do + before do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:publish_at, :as => :datetime, :include_blank => true)) + end + end + + it 'should have a blank select option' do + output_buffer.should have_tag("option[@value='']", "") + end + end + + describe 'inputs order' do + it 'should have a default' do + semantic_form_for(@new_post) do |builder| + self.should_receive(:select_year).once.ordered.and_return('') + self.should_receive(:select_month).once.ordered.and_return('') + self.should_receive(:select_day).once.ordered.and_return('') + builder.input(:publish_at, :as => :datetime) + end + end + + it 'should be specified with :order option' do + I18n.backend.store_translations 'en', :date => { :order => [:month, :year, :day] } + semantic_form_for(@new_post) do |builder| + self.should_receive(:select_month).once.ordered.and_return('') + self.should_receive(:select_year).once.ordered.and_return('') + self.should_receive(:select_day).once.ordered.and_return('') + builder.input(:publish_at, :as => :datetime) + end + end + + it 'should be changed through I18n' do + semantic_form_for(@new_post) do |builder| + self.should_receive(:select_day).once.ordered.and_return('') + self.should_receive(:select_month).once.ordered.and_return('') + self.should_receive(:select_year).once.ordered.and_return('') + builder.input(:publish_at, :as => :datetime, :order => [:day, :month, :year]) + end + end + end + + describe 'when the locale changes the label text' do + before do + I18n.backend.store_translations 'en', :datetime => {:prompts => { + :year => 'The Year', :month => 'The Month', :day => 'The Day', + :hour => 'The Hour', :minute => 'The Minute' + }} + semantic_form_for(@new_post) do |builder| + concat(builder.input(:publish_at, :as => :datetime)) + end + end + + after do + I18n.backend.store_translations 'en', :formtastic => { + :year => nil, :month => nil, :day => nil, + :hour => nil, :minute => nil + } + end + + it 'should have translated labels for year, month, day, hour and minute' do + output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Year/) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Month/) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Day/) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Hour/) + output_buffer.should have_tag('form li.datetime fieldset ol li label', /The Minute/) + end + end + + describe 'when no object is given' do + before(:each) do + output_buffer.replace '' + semantic_form_for(:project, :url => 'http://test.host') do |@builder| + concat(@builder.input(:publish_at, :as => :datetime)) + end + end + + it 'should have fieldset with legend' do + output_buffer.should have_tag('form li.datetime fieldset legend', /Publish at/) + end + + it 'should have labels for each input' do + output_buffer.should have_tag('form li.datetime fieldset ol li label', :count => 5) + end + + it 'should have selects for each inputs' do + output_buffer.should have_tag('form li.datetime fieldset ol li select', :count => 5) + end + end + end + + describe ':as => :time' do + before do + @new_post.stub!(:publish_at) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :time)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:publish_at, :as => :time)) + end + end + + it 'should have a time class on the wrapper li' do + output_buffer.should have_tag('form li.time') + end + + it 'should have a fieldset inside the li wrapper' do + output_buffer.should have_tag('form li.time fieldset') + end + + it 'should have a legend containing the label text inside the fieldset' do + output_buffer.should have_tag('form li.time fieldset legend', /Publish at/) + end + + it 'should have an ordered list of two items inside the fieldset' do + output_buffer.should have_tag('form li.time fieldset ol') + output_buffer.should have_tag('form li.time fieldset ol li', :count => 2) + end + + it 'should have five labels for hour and minute' do + output_buffer.should have_tag('form li.time fieldset ol li label', :count => 2) + output_buffer.should have_tag('form li.time fieldset ol li label', /hour/i) + output_buffer.should have_tag('form li.time fieldset ol li label', /minute/i) + end + + it 'should have two selects for hour and minute' do + #output_buffer.should have_tag('form li.time fieldset ol li select', :count => 2) + output_buffer.should have_tag('form li.time fieldset ol li', :count => 2) + end + end + + [:boolean_select, :boolean_radio].each do |type| + describe ":as => #{type.inspect}" do + it 'should show a deprecation warning' do + @new_post.stub!(:allow_comments) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean)) + + ::ActiveSupport::Deprecation.should_receive(:warn).with(/select|radio/, anything()) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => type)) + end + end + end + end + + describe ':as => :boolean' do + + before do + @new_post.stub!(:allow_comments) + @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :boolean)) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => :boolean)) + end + end + + it 'should have a boolean class on the wrapper' do + output_buffer.should have_tag('form li.boolean') + end + + it 'should have a post_allow_comments_input id on the wrapper' do + output_buffer.should have_tag('form li#post_allow_comments_input') + end + + it 'should generate a label containing the input' do + output_buffer.should have_tag('form li label') + output_buffer.should have_tag('form li label[@for="post_allow_comments"') + output_buffer.should have_tag('form li label', /Allow comments/) + output_buffer.should have_tag('form li label input[@type="checkbox"]') + end + + it 'should generate a checkbox input' do + output_buffer.should have_tag('form li label input') + output_buffer.should have_tag('form li label input#post_allow_comments') + output_buffer.should have_tag('form li label input[@type="checkbox"]') + output_buffer.should have_tag('form li label input[@name="post[allow_comments]"]') + output_buffer.should have_tag('form li label input[@type="checkbox"][@value="1"]') + end + + it 'should allow checked and unchecked values to be sent' do + semantic_form_for(@new_post) do |builder| + concat(builder.input(:allow_comments, :as => :boolean, :checked_value => 'checked', :unchecked_value => 'unchecked')) + end + + output_buffer.should have_tag('form li label input[@type="checkbox"][@value="checked"]') + output_buffer.should have_tag('form li label input[@type="hidden"][@value="unchecked"]') + end + + it 'should generate a label and a checkbox even if no object is given' do + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.input(:allow_comments, :as => :boolean)) + end + + output_buffer.should have_tag('form li label[@for="project_allow_comments"') + output_buffer.should have_tag('form li label', /Allow comments/) + output_buffer.should have_tag('form li label input[@type="checkbox"]') + + output_buffer.should have_tag('form li label input#project_allow_comments') + output_buffer.should have_tag('form li label input[@type="checkbox"]') + output_buffer.should have_tag('form li label input[@name="project[allow_comments]"]') + end + + end + end + + describe '#inputs' do + + describe 'with a block' do + + describe 'when no options are provided' do + before do + output_buffer.replace 'before_builder' # clear the output buffer and sets before_builder + semantic_form_for(@new_post) do |builder| + @inputs_output = builder.inputs do + concat('hello') + end + end + end + + it 'should output just the content wrapped in inputs, not the whole template' do + output_buffer.should =~ /before_builder/ + @inputs_output.should_not =~ /before_builder/ + end + + it 'should render a fieldset inside the form, with a class of "inputs"' do + output_buffer.should have_tag("form fieldset.inputs") + end + + it 'should render an ol inside the fieldset' do + output_buffer.should have_tag("form fieldset.inputs ol") + end + + it 'should render the contents of the block inside the ol' do + output_buffer.should have_tag("form fieldset.inputs ol", /hello/) + end + + it 'should not render a legend inside the fieldset' do + output_buffer.should_not have_tag("form fieldset.inputs legend") + end + + it 'should render a fieldset even if no object is given' do + semantic_form_for(:project, :url => 'http://test.host/') do |builder| + @inputs_output = builder.inputs do + concat('bye') + end + end + + output_buffer.should have_tag("form fieldset.inputs ol", /bye/) + end + end + + describe 'when a :for option is provided' do + it 'should render nested inputs' do + @bob.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255)) + + semantic_form_for(@new_post) do |builder| + builder.inputs :for => [:author, @bob] do |bob_builder| + concat(bob_builder.input(:login)) + end + end + + output_buffer.should have_tag("form fieldset.inputs #post_author_login") + output_buffer.should_not have_tag("form fieldset.inputs #author_login") + end + + it 'should raise an error if :for and block with no argument is given' do + semantic_form_for(@new_post) do |builder| + proc { + builder.inputs(:for => [:author, @bob]) do + # + end + }.should raise_error(ArgumentError, 'You gave :for option with a block to inputs method, ' << + 'but the block does not accept any argument.') + end + end + + it 'should pass options down to semantic_fields_for' do + @bob.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255)) + + semantic_form_for(@new_post) do |builder| + builder.inputs :for => [:author, @bob], :for_options => { :index => 10 } do |bob_builder| + concat(bob_builder.input(:login)) + end + end + + output_buffer.should have_tag('form fieldset ol li #post_author_10_login') + end + + it 'should not add builder as a fieldset attribute tag' do + semantic_form_for(@new_post) do |builder| + builder.inputs :for => [:author, @bob], :for_options => { :index => 10 } do |bob_builder| + concat('input') + end + end + + output_buffer.should_not have_tag('fieldset[@builder="Formtastic::SemanticFormHelper"]') + end + + it 'should send parent_builder as an option to allow child index interpolation' do + semantic_form_for(@new_post) do |builder| + builder.instance_variable_set('@nested_child_index', 0) + builder.inputs :for => [:author, @bob], :name => 'Author #%i' do |bob_builder| + concat('input') + end + end + + output_buffer.should have_tag('fieldset legend', 'Author #1') + end + + it 'should also provide child index interpolation when nested child index is a hash' do + semantic_form_for(@new_post) do |builder| + builder.instance_variable_set('@nested_child_index', :author => 10) + builder.inputs :for => [:author, @bob], :name => 'Author #%i' do |bob_builder| + concat('input') + end + end + + output_buffer.should have_tag('fieldset legend', 'Author #11') + end + end + + describe 'when a :name option is provided' do + before do + @legend_text = "Advanced options" + + semantic_form_for(@new_post) do |builder| + builder.inputs :name => @legend_text do + end + end + end + + it 'should render a fieldset inside the form' do + output_buffer.should have_tag("form fieldset legend", /#{@legend_text}/) + end + end + + describe 'when other options are provided' do + before do + @id_option = 'advanced' + @class_option = 'wide' + + semantic_form_for(@new_post) do |builder| + builder.inputs :id => @id_option, :class => @class_option do + end + end + end + + it 'should pass the options into the fieldset tag as attributes' do + output_buffer.should have_tag("form fieldset##{@id_option}") + output_buffer.should have_tag("form fieldset.#{@class_option}") + end + end + + end + + describe 'without a block' do + + before do + Post.stub!(:reflections).and_return({:author => mock('reflection', :macro => :belongs_to), + :comments => mock('reflection', :macro => :has_many) }) + Post.stub!(:content_columns).and_return([mock('column', :name => 'title'), mock('column', :name => 'body'), mock('column', :name => 'created_at')]) + Author.stub!(:find).and_return([@fred, @bob]) + + @new_post.stub!(:title) + @new_post.stub!(:body) + @new_post.stub!(:author_id) + + @new_post.stub!(:column_for_attribute).with(:title).and_return(mock('column', :type => :string, :limit => 255)) + @new_post.stub!(:column_for_attribute).with(:body).and_return(mock('column', :type => :text)) + @new_post.stub!(:column_for_attribute).with(:created_at).and_return(mock('column', :type => :datetime)) + @new_post.stub!(:column_for_attribute).with(:author).and_return(nil) + end + + describe 'with no args' do + before do + semantic_form_for(@new_post) do |builder| + concat(builder.inputs) + end + end + + it 'should render a form' do + output_buffer.should have_tag('form') + end + + it 'should render a fieldset inside the form' do + output_buffer.should have_tag('form > fieldset.inputs') + end + + it 'should not render a legend in the fieldset' do + output_buffer.should_not have_tag('form > fieldset.inputs > legend') + end + + it 'should render an ol in the fieldset' do + output_buffer.should have_tag('form > fieldset.inputs > ol') + end + + it 'should render a list item in the ol for each column and reflection' do + # Remove the :has_many macro and :created_at column + count = Post.content_columns.size + Post.reflections.size - 2 + output_buffer.should have_tag('form > fieldset.inputs > ol > li', :count => count) + end + + it 'should render a string list item for title' do + output_buffer.should have_tag('form > fieldset.inputs > ol > li.string') + end + + it 'should render a text list item for body' do + output_buffer.should have_tag('form > fieldset.inputs > ol > li.text') + end + + it 'should render a select list item for author_id' do + output_buffer.should have_tag('form > fieldset.inputs > ol > li.select', :count => 1) + end + + it 'should not render timestamps inputs by default' do + output_buffer.should_not have_tag('form > fieldset.inputs > ol > li.datetime') + end + end + + describe 'with column names as args' do + describe 'and an object is given' do + it 'should render a form with a fieldset containing two list items' do + semantic_form_for(@new_post) do |builder| + concat(builder.inputs(:title, :body)) + end + + output_buffer.should have_tag('form > fieldset.inputs > ol > li', :count => 2) + output_buffer.should have_tag('form > fieldset.inputs > ol > li.string') + output_buffer.should have_tag('form > fieldset.inputs > ol > li.text') + end + end + + describe 'and no object is given' do + it 'should render a form with a fieldset containing two list items' do + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.inputs(:title, :body)) + end + + output_buffer.should have_tag('form > fieldset.inputs > ol > li.string', :count => 2) + end + end + end + + describe 'when a :for option is provided' do + describe 'and an object is given' do + it 'should render nested inputs' do + @bob.stub!(:column_for_attribute).and_return(mock('column', :type => :string, :limit => 255)) + + semantic_form_for(@new_post) do |builder| + concat(builder.inputs(:login, :for => @bob)) + end + + output_buffer.should have_tag("form fieldset.inputs #post_author_login") + output_buffer.should_not have_tag("form fieldset.inputs #author_login") + end + end + + describe 'and no object is given' do + it 'should render nested inputs' do + semantic_form_for(:project, :url => 'http://test.host/') do |builder| + concat(builder.inputs(:login, :for => @bob)) + end + + output_buffer.should have_tag("form fieldset.inputs #project_author_login") + output_buffer.should_not have_tag("form fieldset.inputs #project_login") + end + end + end + + describe 'with column names and an options hash as args' do + before do + semantic_form_for(@new_post) do |builder| + concat(builder.inputs(:title, :body, :name => "Legendary Legend Text", :id => "my-id")) + end + end + + it 'should render a form with a fieldset containing two list items' do + output_buffer.should have_tag('form > fieldset.inputs > ol > li', :count => 2) + end + + it 'should pass the options down to the fieldset' do + output_buffer.should have_tag('form > fieldset#my-id.inputs') + end + + it 'should use the special :name option as a text for the legend tag' do + output_buffer.should have_tag('form > fieldset#my-id.inputs > legend', /Legendary Legend Text/) + end + end + + end + + end + + describe '#buttons' do + + describe 'with a block' do + describe 'when no options are provided' do + before do + semantic_form_for(@new_post) do |builder| + builder.buttons do + concat('hello') + end + end + end + + it 'should render a fieldset inside the form, with a class of "inputs"' do + output_buffer.should have_tag("form fieldset.buttons") + end + + it 'should render an ol inside the fieldset' do + output_buffer.should have_tag("form fieldset.buttons ol") + end + + it 'should render the contents of the block inside the ol' do + output_buffer.should have_tag("form fieldset.buttons ol", /hello/) + end + + it 'should not render a legend inside the fieldset' do + output_buffer.should_not have_tag("form fieldset.buttons legend") + end + end + + describe 'when a :name option is provided' do + before do + @legend_text = "Advanced options" + + semantic_form_for(@new_post) do |builder| + builder.buttons :name => @legend_text do + end + end + end + it 'should render a fieldset inside the form' do + output_buffer.should have_tag("form fieldset legend", /#{@legend_text}/) + end + end + + describe 'when other options are provided' do + before do + @id_option = 'advanced' + @class_option = 'wide' + + semantic_form_for(@new_post) do |builder| + builder.buttons :id => @id_option, :class => @class_option do + end + end + end + it 'should pass the options into the fieldset tag as attributes' do + output_buffer.should have_tag("form fieldset##{@id_option}") + output_buffer.should have_tag("form fieldset.#{@class_option}") + end + end + + end + + describe 'without a block' do + + describe 'with no args (default buttons)' do + + before do + semantic_form_for(@new_post) do |builder| + concat(builder.buttons) + end + end + + it 'should render a form' do + output_buffer.should have_tag('form') + end + + it 'should render a buttons fieldset inside the form' do + output_buffer.should have_tag('form fieldset.buttons') + end + + it 'should not render a legend in the fieldset' do + output_buffer.should_not have_tag('form fieldset.buttons legend') + end + + it 'should render an ol in the fieldset' do + output_buffer.should have_tag('form fieldset.buttons ol') + end + + it 'should render a list item in the ol for each default button' do + output_buffer.should have_tag('form fieldset.buttons ol li', :count => 1) + end + + it 'should render a commit list item for the commit button' do + output_buffer.should have_tag('form fieldset.buttons ol li.commit') + end + + end + + describe 'with button names as args' do + + before do + semantic_form_for(@new_post) do |builder| + concat(builder.buttons(:commit)) + end + end + + it 'should render a form with a fieldset containing a list item for each button arg' do + output_buffer.should have_tag('form > fieldset.buttons > ol > li', :count => 1) + output_buffer.should have_tag('form > fieldset.buttons > ol > li.commit') + end + + end + + describe 'with button names as args and an options hash' do + + before do + semantic_form_for(@new_post) do |builder| + concat(builder.buttons(:commit, :name => "Now click a button", :id => "my-id")) + end + end + + it 'should render a form with a fieldset containing a list item for each button arg' do + output_buffer.should have_tag('form > fieldset.buttons > ol > li', :count => 1) + output_buffer.should have_tag('form > fieldset.buttons > ol > li.commit', :count => 1) + end + + it 'should pass the options down to the fieldset' do + output_buffer.should have_tag('form > fieldset#my-id.buttons') + end + + it 'should use the special :name option as a text for the legend tag' do + output_buffer.should have_tag('form > fieldset#my-id.buttons > legend', /Now click a button/) + end + + end + + end + + end + + describe '#commit_button' do + + describe 'when used on any record' do + + before do + @new_post.stub!(:new_record?).and_return(false) + semantic_form_for(@new_post) do |builder| + concat(builder.commit_button) + end + end + + it 'should render a commit li' do + output_buffer.should have_tag('li.commit') + end + + it 'should render an input with a type attribute of "submit"' do + output_buffer.should have_tag('li.commit input[@type="submit"]') + end + + it 'should render an input with a name attribute of "commit"' do + output_buffer.should have_tag('li.commit input[@name="commit"]') + end + + it 'should pass options given in :button_html to the button' do + @new_post.stub!(:new_record?).and_return(false) + semantic_form_for(@new_post) do |builder| + concat(builder.commit_button('text', :button_html => {:class => 'my_class', :id => 'my_id'})) + end + + output_buffer.should have_tag('li.commit input#my_id') + output_buffer.should have_tag('li.commit input.my_class') + end + + end + + describe 'when the first option is a string and the second is a hash' do + + before do + @new_post.stub!(:new_record?).and_return(false) + semantic_form_for(@new_post) do |builder| + concat(builder.commit_button("a string", :button_html => { :class => "pretty"})) + end + end + + it "should render the string as the value of the button" do + output_buffer.should have_tag('li input[@value="a string"]') + end + + it "should deal with the options hash" do + output_buffer.should have_tag('li input.pretty') + end + + end + + describe 'when the first option is a hash' do + + before do + @new_post.stub!(:new_record?).and_return(false) + semantic_form_for(@new_post) do |builder| + concat(builder.commit_button(:button_html => { :class => "pretty"})) + end + end + + it "should deal with the options hash" do + output_buffer.should have_tag('li input.pretty') + end + + end + + describe 'when used on an existing record' do + + it 'should render an input with a value attribute of "Save Post"' do + @new_post.stub!(:new_record?).and_return(false) + semantic_form_for(@new_post) do |builder| + concat(builder.commit_button) + end + output_buffer.should have_tag('li.commit input[@value="Save Post"]') + end + + describe 'when the locale sets the label text' do + before do + I18n.backend.store_translations 'en', :formtastic => {:save => 'Save Changes To' } + @new_post.stub!(:new_record?).and_return(false) + semantic_form_for(@new_post) do |builder| + concat(builder.commit_button) + end + end + + after do + I18n.backend.store_translations 'en', :formtastic => {:save => nil} + end + + it 'should allow translation of the labels' do + output_buffer.should have_tag('li.commit input[@value="Save Changes To Post"]') + end + end + end + + describe 'when used on a new record' do + + it 'should render an input with a value attribute of "Create Post"' do + @new_post.stub!(:new_record?).and_return(true) + semantic_form_for(@new_post) do |builder| + concat(builder.commit_button) + end + output_buffer.should have_tag('li.commit input[@value="Create Post"]') + end + + describe 'when the locale sets the label text' do + before do + I18n.backend.store_translations 'en', :formtastic => {:create => 'Make' } + semantic_form_for(@new_post) do |builder| + concat(builder.commit_button) + end + end + + after do + I18n.backend.store_translations 'en', :formtastic => {:create => nil} + end + + it 'should allow translation of the labels' do + output_buffer.should have_tag('li.commit input[@value="Make Post"]') + end + end + + end + + describe 'when used without object' do + + it 'should render an input with a value attribute of "Submit"' do + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.commit_button) + end + + output_buffer.should have_tag('li.commit input[@value="Submit Project"]') + end + + describe 'when the locale sets the label text' do + before do + I18n.backend.store_translations 'en', :formtastic => { :submit => 'Send' } + semantic_form_for(:project, :url => 'http://test.host') do |builder| + concat(builder.commit_button) + end + end + + after do + I18n.backend.store_translations 'en', :formtastic => {:submit => nil} + end + + it 'should allow translation of the labels' do + output_buffer.should have_tag('li.commit input[@value="Send Project"]') + end + end + + end + + end + + end + +end diff --git a/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/spec/test_helper.rb b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/spec/test_helper.rb new file mode 100644 index 000000000..93fac34c2 --- /dev/null +++ b/test/rails_root/vendor/gems/justinfrench-formtastic-0.2.1/spec/test_helper.rb @@ -0,0 +1,14 @@ +require 'rubygems' +require 'spec' +require 'activesupport' +require 'active_support' +require 'actionpack' +require 'action_controller' +require 'action_view' +require 'rexml/document' +require 'rspec_hpricot_matchers' +Spec::Runner.configure do |config| + config.include(RspecHpricotMatchers) +end + +$LOAD_PATH.unshift(File.dirname(__FILE__) + '/../lib')