jintastic 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. data/.document +5 -0
  2. data/.gitignore +5 -0
  3. data/MIT-LICENSE +21 -0
  4. data/README.md +97 -0
  5. data/Rakefile +59 -0
  6. data/VERSION.yml +5 -0
  7. data/assets/app/views/jintastic/_in_place_editor.html.erb +16 -0
  8. data/assets/public/javascripts/jintastic.js +35 -0
  9. data/config/locale/en.yml +4 -0
  10. data/init.rb +3 -0
  11. data/jintastic.gemspec +111 -0
  12. data/lib/jintastic.rb +61 -0
  13. data/test/jintastic_test.rb +7 -0
  14. data/test/test_helper.rb +10 -0
  15. data/vendor/plugins/formtastic/.gitignore +5 -0
  16. data/vendor/plugins/formtastic/MIT-LICENSE +20 -0
  17. data/vendor/plugins/formtastic/README.textile +553 -0
  18. data/vendor/plugins/formtastic/RELEASE_PROCESS +11 -0
  19. data/vendor/plugins/formtastic/Rakefile +101 -0
  20. data/vendor/plugins/formtastic/VERSION.yml +4 -0
  21. data/vendor/plugins/formtastic/formtastic.gemspec +142 -0
  22. data/vendor/plugins/formtastic/generators/form/USAGE +16 -0
  23. data/vendor/plugins/formtastic/generators/form/form_generator.rb +120 -0
  24. data/vendor/plugins/formtastic/generators/form/templates/view__form.html.erb +5 -0
  25. data/vendor/plugins/formtastic/generators/form/templates/view__form.html.haml +4 -0
  26. data/vendor/plugins/formtastic/generators/formtastic/formtastic_generator.rb +24 -0
  27. data/vendor/plugins/formtastic/generators/formtastic/templates/formtastic.css +144 -0
  28. data/vendor/plugins/formtastic/generators/formtastic/templates/formtastic_changes.css +10 -0
  29. data/vendor/plugins/formtastic/generators/formtastic/templates/formtastic_config.rb +54 -0
  30. data/vendor/plugins/formtastic/generators/formtastic_stylesheets/formtastic_stylesheets_generator.rb +16 -0
  31. data/vendor/plugins/formtastic/install.rb +2 -0
  32. data/vendor/plugins/formtastic/lib/formtastic.rb +1687 -0
  33. data/vendor/plugins/formtastic/lib/formtastic/i18n.rb +32 -0
  34. data/vendor/plugins/formtastic/lib/locale/en.yml +8 -0
  35. data/vendor/plugins/formtastic/rails/init.rb +3 -0
  36. data/vendor/plugins/formtastic/spec/buttons_spec.rb +149 -0
  37. data/vendor/plugins/formtastic/spec/commit_button_spec.rb +369 -0
  38. data/vendor/plugins/formtastic/spec/custom_builder_spec.rb +62 -0
  39. data/vendor/plugins/formtastic/spec/custom_macros.rb +561 -0
  40. data/vendor/plugins/formtastic/spec/defaults_spec.rb +20 -0
  41. data/vendor/plugins/formtastic/spec/error_proc_spec.rb +27 -0
  42. data/vendor/plugins/formtastic/spec/errors_spec.rb +85 -0
  43. data/vendor/plugins/formtastic/spec/form_helper_spec.rb +126 -0
  44. data/vendor/plugins/formtastic/spec/i18n_spec.rb +131 -0
  45. data/vendor/plugins/formtastic/spec/include_blank_spec.rb +70 -0
  46. data/vendor/plugins/formtastic/spec/input_spec.rb +628 -0
  47. data/vendor/plugins/formtastic/spec/inputs/boolean_input_spec.rb +93 -0
  48. data/vendor/plugins/formtastic/spec/inputs/check_boxes_input_spec.rb +162 -0
  49. data/vendor/plugins/formtastic/spec/inputs/country_input_spec.rb +80 -0
  50. data/vendor/plugins/formtastic/spec/inputs/date_input_spec.rb +60 -0
  51. data/vendor/plugins/formtastic/spec/inputs/datetime_input_spec.rb +169 -0
  52. data/vendor/plugins/formtastic/spec/inputs/file_input_spec.rb +33 -0
  53. data/vendor/plugins/formtastic/spec/inputs/hidden_input_spec.rb +52 -0
  54. data/vendor/plugins/formtastic/spec/inputs/numeric_input_spec.rb +44 -0
  55. data/vendor/plugins/formtastic/spec/inputs/password_input_spec.rb +46 -0
  56. data/vendor/plugins/formtastic/spec/inputs/radio_input_spec.rb +149 -0
  57. data/vendor/plugins/formtastic/spec/inputs/select_input_spec.rb +459 -0
  58. data/vendor/plugins/formtastic/spec/inputs/string_input_spec.rb +47 -0
  59. data/vendor/plugins/formtastic/spec/inputs/text_input_spec.rb +33 -0
  60. data/vendor/plugins/formtastic/spec/inputs/time_input_spec.rb +44 -0
  61. data/vendor/plugins/formtastic/spec/inputs/time_zone_input_spec.rb +102 -0
  62. data/vendor/plugins/formtastic/spec/inputs_spec.rb +395 -0
  63. data/vendor/plugins/formtastic/spec/label_spec.rb +48 -0
  64. data/vendor/plugins/formtastic/spec/semantic_errors_spec.rb +98 -0
  65. data/vendor/plugins/formtastic/spec/semantic_fields_for_spec.rb +44 -0
  66. data/vendor/plugins/formtastic/spec/spec.opts +2 -0
  67. data/vendor/plugins/formtastic/spec/spec_helper.rb +218 -0
  68. data/vendor/plugins/formtastic/uninstall.rb +1 -0
  69. metadata +132 -0
@@ -0,0 +1,10 @@
1
+ /* -------------------------------------------------------------------------------------------------
2
+
3
+ Load this stylesheet after formtastic.css in your layouts to override the CSS to suit your needs.
4
+ This will allow you to update formtastic.css with new releases without clobbering your own changes.
5
+
6
+ For example, to make the inline hint paragraphs a little darker in color than the standard #666:
7
+
8
+ form.formtastic fieldset ol li p.inline-hints { color:#333; }
9
+
10
+ --------------------------------------------------------------------------------------------------*/
@@ -0,0 +1,54 @@
1
+ # Set the default text field size when input is a string. Default is 50.
2
+ # Formtastic::SemanticFormBuilder.default_text_field_size = 50
3
+
4
+ # Set the default text area height when input is a text. Default is 20.
5
+ # Formtastic::SemanticFormBuilder.default_text_area_height = 5
6
+
7
+ # Should all fields be considered "required" by default?
8
+ # Defaults to true, see ValidationReflection notes below.
9
+ # Formtastic::SemanticFormBuilder.all_fields_required_by_default = true
10
+
11
+ # Should select fields have a blank option/prompt by default?
12
+ # Defaults to true.
13
+ # Formtastic::SemanticFormBuilder.include_blank_for_select_by_default = true
14
+
15
+ # Set the string that will be appended to the labels/fieldsets which are required
16
+ # It accepts string or procs and the default is a localized version of
17
+ # '<abbr title="required">*</abbr>'. In other words, if you configure formtastic.required
18
+ # in your locale, it will replace the abbr title properly. But if you don't want to use
19
+ # abbr tag, you can simply give a string as below
20
+ # Formtastic::SemanticFormBuilder.required_string = "(required)"
21
+
22
+ # Set the string that will be appended to the labels/fieldsets which are optional
23
+ # Defaults to an empty string ("") and also accepts procs (see required_string above)
24
+ # Formtastic::SemanticFormBuilder.optional_string = "(optional)"
25
+
26
+ # Set the way inline errors will be displayed.
27
+ # Defaults to :sentence, valid options are :sentence, :list and :none
28
+ # Formtastic::SemanticFormBuilder.inline_errors = :sentence
29
+
30
+ # Set the method to call on label text to transform or format it for human-friendly
31
+ # reading when formtastic is user without object. Defaults to :humanize.
32
+ # Formtastic::SemanticFormBuilder.label_str_method = :humanize
33
+
34
+ # Set the array of methods to try calling on parent objects in :select and :radio inputs
35
+ # for the text inside each @<option>@ tag or alongside each radio @<input>@. The first method
36
+ # that is found on the object will be used.
37
+ # Defaults to ["to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"]
38
+ # Formtastic::SemanticFormBuilder.collection_label_methods = [
39
+ # "to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"]
40
+
41
+ # Formtastic by default renders inside li tags the input, hints and then
42
+ # errors messages. Sometimes you want the hints to be rendered first than
43
+ # the input, in the following order: hints, input and errors. You can
44
+ # customize it doing just as below:
45
+ # Formtastic::SemanticFormBuilder.inline_order = [:input, :hints, :errors]
46
+
47
+ # Specifies if labels/hints for input fields automatically be looked up using I18n.
48
+ # Default value: false. Overridden for specific fields by setting value to true,
49
+ # i.e. :label => true, or :hint => true (or opposite depending on initialized value)
50
+ # Formtastic::SemanticFormBuilder.i18n_lookups_by_default = false
51
+
52
+ # You can add custom inputs or override parts of Formtastic by subclassing SemanticFormBuilder and
53
+ # specifying that class here. Defaults to SemanticFormBuilder.
54
+ # Formtastic::SemanticFormHelper.builder = MyCustomBuilder
@@ -0,0 +1,16 @@
1
+ class FormtasticStylesheetsGenerator < Rails::Generator::Base
2
+
3
+ def initialize(*runtime_args)
4
+ puts %q{
5
+ ===================================================
6
+ Please run `./script/generate formtastic` instead.
7
+ ===================================================
8
+ }
9
+ end
10
+
11
+ def manifest
12
+ record do |m|
13
+ end
14
+ end
15
+
16
+ end
@@ -0,0 +1,2 @@
1
+ puts "Run `./script/generate formtastic` if you want (copies optional config file and some stylesheets into your app)"
2
+ puts "Run `./script/generate form MODEL_NAME` to generate some semantic form markup for any existing model(s) (optional)"
@@ -0,0 +1,1687 @@
1
+ # coding: utf-8
2
+ require File.join(File.dirname(__FILE__), *%w[formtastic i18n])
3
+
4
+ module Formtastic #:nodoc:
5
+
6
+ class SemanticFormBuilder < ActionView::Helpers::FormBuilder
7
+
8
+ @@default_text_field_size = 50
9
+ @@default_text_area_height = 20
10
+ @@all_fields_required_by_default = true
11
+ @@include_blank_for_select_by_default = true
12
+ @@required_string = proc { %{<abbr title="#{::Formtastic::I18n.t(:required)}">*</abbr>} }
13
+ @@optional_string = ''
14
+ @@inline_errors = :sentence
15
+ @@label_str_method = :humanize
16
+ @@collection_label_methods = %w[to_label display_name full_name name title username login value to_s]
17
+ @@inline_order = [ :input, :hints, :errors ]
18
+ @@file_methods = [ :file?, :public_filename, :filename ]
19
+ @@priority_countries = ["Australia", "Canada", "United Kingdom", "United States"]
20
+ @@i18n_lookups_by_default = false
21
+ @@default_commit_button_accesskey = nil
22
+
23
+ cattr_accessor :default_text_field_size, :default_text_area_height, :all_fields_required_by_default, :include_blank_for_select_by_default,
24
+ :required_string, :optional_string, :inline_errors, :label_str_method, :collection_label_methods,
25
+ :inline_order, :file_methods, :priority_countries, :i18n_lookups_by_default, :default_commit_button_accesskey
26
+
27
+ RESERVED_COLUMNS = [:created_at, :updated_at, :created_on, :updated_on, :lock_version, :version]
28
+
29
+ INLINE_ERROR_TYPES = [:sentence, :list, :first]
30
+
31
+ attr_accessor :template
32
+
33
+ # Returns a suitable form input for the given +method+, using the database column information
34
+ # and other factors (like the method name) to figure out what you probably want.
35
+ #
36
+ # Options:
37
+ #
38
+ # * :as - override the input type (eg force a :string to render as a :password field)
39
+ # * :label - use something other than the method name as the label text, when false no label is printed
40
+ # * :required - specify if the column is required (true) or not (false)
41
+ # * :hint - provide some text to hint or help the user provide the correct information for a field
42
+ # * :input_html - provide options that will be passed down to the generated input
43
+ # * :wrapper_html - provide options that will be passed down to the li wrapper
44
+ #
45
+ # Input Types:
46
+ #
47
+ # Most inputs map directly to one of ActiveRecord's column types by default (eg string_input),
48
+ # but there are a few special cases and some simplification (:integer, :float and :decimal
49
+ # columns all map to a single numeric_input, for example).
50
+ #
51
+ # * :select (a select menu for associations) - default to association names
52
+ # * :check_boxes (a set of check_box inputs for associations) - alternative to :select has_many and has_and_belongs_to_many associations
53
+ # * :radio (a set of radio inputs for associations) - alternative to :select belongs_to associations
54
+ # * :time_zone (a select menu with time zones)
55
+ # * :password (a password input) - default for :string column types with 'password' in the method name
56
+ # * :text (a textarea) - default for :text column types
57
+ # * :date (a date select) - default for :date column types
58
+ # * :datetime (a date and time select) - default for :datetime and :timestamp column types
59
+ # * :time (a time select) - default for :time column types
60
+ # * :boolean (a checkbox) - default for :boolean column types (you can also have booleans as :select and :radio)
61
+ # * :string (a text field) - default for :string column types
62
+ # * :numeric (a text field, like string) - default for :integer, :float and :decimal column types
63
+ # * :country (a select menu of country names) - requires a country_select plugin to be installed
64
+ # * :hidden (a hidden field) - creates a hidden field (added for compatibility)
65
+ #
66
+ # Example:
67
+ #
68
+ # <% semantic_form_for @employee do |form| %>
69
+ # <% form.inputs do -%>
70
+ # <%= form.input :secret, :value => "Hello" %>
71
+ # <%= form.input :name, :label => "Full Name" %>
72
+ # <%= form.input :manager_id, :as => :radio %>
73
+ # <%= form.input :hired_at, :as => :date, :label => "Date Hired" %>
74
+ # <%= form.input :phone, :required => false, :hint => "Eg: +1 555 1234" %>
75
+ # <% end %>
76
+ # <% end %>
77
+ #
78
+ def input(method, options = {})
79
+ options[:required] = method_required?(method) unless options.key?(:required)
80
+ options[:as] ||= default_input_type(method, options)
81
+
82
+ html_class = [ options[:as], (options[:required] ? :required : :optional) ]
83
+ html_class << 'error' if @object && @object.respond_to?(:errors) && !@object.errors[method.to_sym].blank?
84
+
85
+ wrapper_html = options.delete(:wrapper_html) || {}
86
+ wrapper_html[:id] ||= generate_html_id(method)
87
+ wrapper_html[:class] = (html_class << wrapper_html[:class]).flatten.compact.join(' ')
88
+
89
+ if options[:input_html] && options[:input_html][:id]
90
+ options[:label_html] ||= {}
91
+ options[:label_html][:for] ||= options[:input_html][:id]
92
+ end
93
+
94
+ input_parts = @@inline_order.dup
95
+ input_parts.delete(:errors) if options[:as] == :hidden
96
+
97
+ list_item_content = input_parts.map do |type|
98
+ send(:"inline_#{type}_for", method, options)
99
+ end.compact.join("\n")
100
+
101
+ return template.content_tag(:li, list_item_content, wrapper_html)
102
+ end
103
+
104
+ # Creates an input fieldset and ol tag wrapping for use around a set of inputs. It can be
105
+ # called either with a block (in which you can do the usual Rails form stuff, HTML, ERB, etc),
106
+ # or with a list of fields. These two examples are functionally equivalent:
107
+ #
108
+ # # With a block:
109
+ # <% semantic_form_for @post do |form| %>
110
+ # <% form.inputs do %>
111
+ # <%= form.input :title %>
112
+ # <%= form.input :body %>
113
+ # <% end %>
114
+ # <% end %>
115
+ #
116
+ # # With a list of fields:
117
+ # <% semantic_form_for @post do |form| %>
118
+ # <%= form.inputs :title, :body %>
119
+ # <% end %>
120
+ #
121
+ # # Output:
122
+ # <form ...>
123
+ # <fieldset class="inputs">
124
+ # <ol>
125
+ # <li class="string">...</li>
126
+ # <li class="text">...</li>
127
+ # </ol>
128
+ # </fieldset>
129
+ # </form>
130
+ #
131
+ # === Quick Forms
132
+ #
133
+ # When called without a block or a field list, an input is rendered for each column in the
134
+ # model's database table, just like Rails' scaffolding. You'll obviously want more control
135
+ # than this in a production application, but it's a great way to get started, then come back
136
+ # later to customise the form with a field list or a block of inputs. Example:
137
+ #
138
+ # <% semantic_form_for @post do |form| %>
139
+ # <%= form.inputs %>
140
+ # <% end %>
141
+ #
142
+ # With a few arguments:
143
+ # <% semantic_form_for @post do |form| %>
144
+ # <%= form.inputs "Post details", :title, :body %>
145
+ # <% end %>
146
+ #
147
+ # === Options
148
+ #
149
+ # All options (with the exception of :name/:title) are passed down to the fieldset as HTML
150
+ # attributes (id, class, style, etc). If provided, the :name/:title option is passed into a
151
+ # legend tag inside the fieldset.
152
+ #
153
+ # # With a block:
154
+ # <% semantic_form_for @post do |form| %>
155
+ # <% form.inputs :name => "Create a new post", :style => "border:1px;" do %>
156
+ # ...
157
+ # <% end %>
158
+ # <% end %>
159
+ #
160
+ # # With a list (the options must come after the field list):
161
+ # <% semantic_form_for @post do |form| %>
162
+ # <%= form.inputs :title, :body, :name => "Create a new post", :style => "border:1px;" %>
163
+ # <% end %>
164
+ #
165
+ # # ...or the equivalent:
166
+ # <% semantic_form_for @post do |form| %>
167
+ # <%= form.inputs "Create a new post", :title, :body, :style => "border:1px;" %>
168
+ # <% end %>
169
+ #
170
+ # === It's basically a fieldset!
171
+ #
172
+ # Instead of hard-coding fieldsets & legends into your form to logically group related fields,
173
+ # use inputs:
174
+ #
175
+ # <% semantic_form_for @post do |f| %>
176
+ # <% f.inputs do %>
177
+ # <%= f.input :title %>
178
+ # <%= f.input :body %>
179
+ # <% end %>
180
+ # <% f.inputs :name => "Advanced", :id => "advanced" do %>
181
+ # <%= f.input :created_at %>
182
+ # <%= f.input :user_id, :label => "Author" %>
183
+ # <% end %>
184
+ # <% f.inputs "Extra" do %>
185
+ # <%= f.input :update_at %>
186
+ # <% end %>
187
+ # <% end %>
188
+ #
189
+ # # Output:
190
+ # <form ...>
191
+ # <fieldset class="inputs">
192
+ # <ol>
193
+ # <li class="string">...</li>
194
+ # <li class="text">...</li>
195
+ # </ol>
196
+ # </fieldset>
197
+ # <fieldset class="inputs" id="advanced">
198
+ # <legend><span>Advanced</span></legend>
199
+ # <ol>
200
+ # <li class="datetime">...</li>
201
+ # <li class="select">...</li>
202
+ # </ol>
203
+ # </fieldset>
204
+ # <fieldset class="inputs">
205
+ # <legend><span>Extra</span></legend>
206
+ # <ol>
207
+ # <li class="datetime">...</li>
208
+ # </ol>
209
+ # </fieldset>
210
+ # </form>
211
+ #
212
+ # === Nested attributes
213
+ #
214
+ # As in Rails, you can use semantic_fields_for to nest attributes:
215
+ #
216
+ # <% semantic_form_for @post do |form| %>
217
+ # <%= form.inputs :title, :body %>
218
+ #
219
+ # <% form.semantic_fields_for :author, @bob do |author_form| %>
220
+ # <% author_form.inputs do %>
221
+ # <%= author_form.input :first_name, :required => false %>
222
+ # <%= author_form.input :last_name %>
223
+ # <% end %>
224
+ # <% end %>
225
+ # <% end %>
226
+ #
227
+ # But this does not look formtastic! This is equivalent:
228
+ #
229
+ # <% semantic_form_for @post do |form| %>
230
+ # <%= form.inputs :title, :body %>
231
+ # <% form.inputs :for => [ :author, @bob ] do |author_form| %>
232
+ # <%= author_form.input :first_name, :required => false %>
233
+ # <%= author_form.input :last_name %>
234
+ # <% end %>
235
+ # <% end %>
236
+ #
237
+ # And if you don't need to give options to your input call, you could do it
238
+ # in just one line:
239
+ #
240
+ # <% semantic_form_for @post do |form| %>
241
+ # <%= form.inputs :title, :body %>
242
+ # <%= form.inputs :first_name, :last_name, :for => @bob %>
243
+ # <% end %>
244
+ #
245
+ # Just remember that calling inputs generates a new fieldset to wrap your
246
+ # inputs. If you have two separate models, but, semantically, on the page
247
+ # they are part of the same fieldset, you should use semantic_fields_for
248
+ # instead (just as you would do with Rails' form builder).
249
+ #
250
+ def inputs(*args, &block)
251
+ title = field_set_title_from_args(*args)
252
+ html_options = args.extract_options!
253
+ html_options[:class] ||= "inputs"
254
+ html_options[:name] = title
255
+
256
+ if html_options[:for] # Nested form
257
+ inputs_for_nested_attributes(*(args << html_options), &block)
258
+ elsif block_given?
259
+ field_set_and_list_wrapping(*(args << html_options), &block)
260
+ else
261
+ if @object && args.empty?
262
+ args = self.association_columns(:belongs_to)
263
+ args += self.content_columns
264
+ args -= RESERVED_COLUMNS
265
+ args.compact!
266
+ end
267
+ legend = args.shift if args.first.is_a?(::String)
268
+ contents = args.collect { |method| input(method.to_sym) }
269
+ args.unshift(legend) if legend.present?
270
+
271
+ field_set_and_list_wrapping(*((args << html_options) << contents))
272
+ end
273
+ end
274
+ alias :input_field_set :inputs
275
+
276
+ # Creates a fieldset and ol tag wrapping for form buttons / actions as list items.
277
+ # See inputs documentation for a full example. The fieldset's default class attriute
278
+ # is set to "buttons".
279
+ #
280
+ # See inputs for html attributes and special options.
281
+ def buttons(*args, &block)
282
+ html_options = args.extract_options!
283
+ html_options[:class] ||= "buttons"
284
+
285
+ if block_given?
286
+ field_set_and_list_wrapping(html_options, &block)
287
+ else
288
+ args = [:commit] if args.empty?
289
+ contents = args.map { |button_name| send(:"#{button_name}_button") }
290
+ field_set_and_list_wrapping(html_options, contents)
291
+ end
292
+ end
293
+ alias :button_field_set :buttons
294
+
295
+ # Creates a submit input tag with the value "Save [model name]" (for existing records) or
296
+ # "Create [model name]" (for new records) by default:
297
+ #
298
+ # <%= form.commit_button %> => <input name="commit" type="submit" value="Save Post" />
299
+ #
300
+ # The value of the button text can be overridden:
301
+ #
302
+ # <%= form.commit_button "Go" %> => <input name="commit" type="submit" value="Go" class="{create|update|submit}" />
303
+ # <%= form.commit_button :label => "Go" %> => <input name="commit" type="submit" value="Go" class="{create|update|submit}" />
304
+ #
305
+ # And you can pass html atributes down to the input, with or without the button text:
306
+ #
307
+ # <%= form.commit_button "Go" %> => <input name="commit" type="submit" value="Go" class="{create|update|submit}" />
308
+ # <%= form.commit_button :class => "pretty" %> => <input name="commit" type="submit" value="Save Post" class="pretty {create|update|submit}" />
309
+ #
310
+ def commit_button(*args)
311
+ options = args.extract_options!
312
+ text = options.delete(:label) || args.shift
313
+
314
+ if @object && @object.respond_to?(:new_record?)
315
+ key = @object.new_record? ? :create : :update
316
+ object_name = @object.class.name.underscore.humanize # TODO Rails Bug: should be able to call @object.class.human_name, see http://github.com/justinfrench/formtastic/issues/#issue/153 revisit for Rails 3
317
+ else
318
+ key = :submit
319
+ object_name = @object_name.to_s.send(@@label_str_method)
320
+ end
321
+
322
+ text = (self.localized_string(key, text, :action, :model => object_name) ||
323
+ ::Formtastic::I18n.t(key, :model => object_name)) unless text.is_a?(::String)
324
+
325
+ button_html = options.delete(:button_html) || {}
326
+ button_html.merge!(:class => [button_html[:class], key].compact.join(' '))
327
+ element_class = ['commit', options.delete(:class)].compact.join(' ') # TODO: Add class reflecting on form action.
328
+ accesskey = (options.delete(:accesskey) || @@default_commit_button_accesskey) unless button_html.has_key?(:accesskey)
329
+ button_html = button_html.merge(:accesskey => accesskey) if accesskey
330
+ template.content_tag(:li, self.submit(text, button_html), :class => element_class)
331
+ end
332
+
333
+ # A thin wrapper around #fields_for to set :builder => Formtastic::SemanticFormBuilder
334
+ # for nesting forms:
335
+ #
336
+ # # Example:
337
+ # <% semantic_form_for @post do |post| %>
338
+ # <% post.semantic_fields_for :author do |author| %>
339
+ # <% author.inputs :name %>
340
+ # <% end %>
341
+ # <% end %>
342
+ #
343
+ # # Output:
344
+ # <form ...>
345
+ # <fieldset class="inputs">
346
+ # <ol>
347
+ # <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
348
+ # </ol>
349
+ # </fieldset>
350
+ # </form>
351
+ #
352
+ def semantic_fields_for(record_or_name_or_array, *args, &block)
353
+ opts = args.extract_options!
354
+ opts[:builder] ||= Formtastic::SemanticFormHelper.builder
355
+ args.push(opts)
356
+ fields_for(record_or_name_or_array, *args, &block)
357
+ end
358
+
359
+ # Generates the label for the input. It also accepts the same arguments as
360
+ # Rails label method. It has three options that are not supported by Rails
361
+ # label method:
362
+ #
363
+ # * :required - Appends an abbr tag if :required is true
364
+ # * :label - An alternative form to give the label content. Whenever label
365
+ # is false, a blank string is returned.
366
+ # * :input_name - Gives the input to match for. This is needed when you want to
367
+ # to call f.label :authors but it should match :author_ids.
368
+ #
369
+ # == Examples
370
+ #
371
+ # f.label :title # like in rails, except that it searches the label on I18n API too
372
+ #
373
+ # f.label :title, "Your post title"
374
+ # f.label :title, :label => "Your post title" # Added for formtastic API
375
+ #
376
+ # f.label :title, :required => true # Returns <label>Title<abbr title="required">*</abbr></label>
377
+ #
378
+ def label(method, options_or_text=nil, options=nil)
379
+ if options_or_text.is_a?(Hash)
380
+ return "" if options_or_text[:label] == false
381
+ options = options_or_text
382
+ text = options.delete(:label)
383
+ else
384
+ text = options_or_text
385
+ options ||= {}
386
+ end
387
+ text = localized_string(method, text, :label) || humanized_attribute_name(method)
388
+ text += required_or_optional_string(options.delete(:required))
389
+
390
+ # special case for boolean (checkbox) labels, which have a nested input
391
+ text = (options.delete(:label_prefix_for_nested_input) || "") + text
392
+
393
+ input_name = options.delete(:input_name) || method
394
+ super(input_name, text, options)
395
+ end
396
+
397
+ # Generates error messages for the given method. Errors can be shown as list,
398
+ # as sentence or just the first error can be displayed. If :none is set, no error is shown.
399
+ #
400
+ # This method is also aliased as errors_on, so you can call on your custom
401
+ # inputs as well:
402
+ #
403
+ # semantic_form_for :post do |f|
404
+ # f.text_field(:body)
405
+ # f.errors_on(:body)
406
+ # end
407
+ #
408
+ def inline_errors_for(method, options = nil) #:nodoc:
409
+ if render_inline_errors?
410
+ errors = @object.errors[method.to_sym]
411
+ send(:"error_#{@@inline_errors}", [*errors]) if errors.present?
412
+ else
413
+ nil
414
+ end
415
+ end
416
+ alias :errors_on :inline_errors_for
417
+
418
+ # Generates error messages for given method names and for base.
419
+ # You can pass a hash with html options that will be added to ul tag
420
+ #
421
+ # == Examples
422
+ #
423
+ # f.semantic_errors # This will show only errors on base
424
+ # f.semantic_errors :state # This will show errors on base and state
425
+ # f.semantic_errors :state, :class => "awesome" # errors will be rendered in ul.awesome
426
+ #
427
+ def semantic_errors(*args)
428
+ html_options = args.extract_options!
429
+ full_errors = args.inject([]) do |array, method|
430
+ attribute = localized_string(method, method.to_sym, :label) || humanized_attribute_name(method)
431
+ errors = Array(@object.errors[method.to_sym]).to_sentence
432
+ errors.present? ? array << [attribute, errors].join(" ") : array ||= []
433
+ end
434
+ full_errors << @object.errors.on_base
435
+ full_errors.flatten!
436
+ full_errors.compact!
437
+ return nil if full_errors.blank?
438
+ html_options[:class] ||= "errors"
439
+ template.content_tag(:ul, html_options) do
440
+ full_errors.map { |error| template.content_tag(:li, error) }.join
441
+ end
442
+ end
443
+
444
+ protected
445
+
446
+ def render_inline_errors?
447
+ @object && @object.respond_to?(:errors) && INLINE_ERROR_TYPES.include?(@@inline_errors)
448
+ end
449
+
450
+ # Collects content columns (non-relation columns) for the current form object class.
451
+ #
452
+ def content_columns #:nodoc:
453
+ self.model_name.constantize.content_columns.collect { |c| c.name.to_sym }.compact rescue []
454
+ end
455
+
456
+ # Collects association columns (relation columns) for the current form object class.
457
+ #
458
+ def association_columns(*by_associations) #:nodoc:
459
+ if @object.present?
460
+ @object.class.reflections.collect do |name, _|
461
+ if by_associations.present?
462
+ name if by_associations.include?(_.macro)
463
+ else
464
+ name
465
+ end
466
+ end.compact
467
+ else
468
+ []
469
+ end
470
+ end
471
+
472
+ # Prepare options to be sent to label
473
+ #
474
+ def options_for_label(options) #:nodoc:
475
+ options.slice(:label, :required).merge!(options.fetch(:label_html, {}))
476
+ end
477
+
478
+ # Deals with :for option when it's supplied to inputs methods. Additional
479
+ # options to be passed down to :for should be supplied using :for_options
480
+ # key.
481
+ #
482
+ # It should raise an error if a block with arity zero is given.
483
+ #
484
+ def inputs_for_nested_attributes(*args, &block) #:nodoc:
485
+ options = args.extract_options!
486
+ args << options.merge!(:parent => { :builder => self, :for => options[:for] })
487
+
488
+ fields_for_block = if block_given?
489
+ raise ArgumentError, 'You gave :for option with a block to inputs method, ' <<
490
+ 'but the block does not accept any argument.' if block.arity <= 0
491
+
492
+ proc { |f| f.inputs(*args){ block.call(f) } }
493
+ else
494
+ proc { |f| f.inputs(*args) }
495
+ end
496
+
497
+ fields_for_args = [options.delete(:for), options.delete(:for_options) || {}].flatten
498
+ semantic_fields_for(*fields_for_args, &fields_for_block)
499
+ end
500
+
501
+ # Remove any Formtastic-specific options before passing the down options.
502
+ #
503
+ def strip_formtastic_options(options) #:nodoc:
504
+ options.except(:value_method, :label_method, :collection, :required, :label,
505
+ :as, :hint, :input_html, :label_html, :value_as_class)
506
+ end
507
+
508
+ # Determins if the attribute (eg :title) should be considered required or not.
509
+ #
510
+ # * if the :required option was provided in the options hash, the true/false value will be
511
+ # returned immediately, allowing the view to override any guesswork that follows:
512
+ #
513
+ # * if the :required option isn't provided in the options hash, and the ValidationReflection
514
+ # plugin is installed (http://github.com/redinger/validation_reflection), true is returned
515
+ # if the validates_presence_of macro has been used in the class for this attribute, or false
516
+ # otherwise.
517
+ #
518
+ # * if the :required option isn't provided, and the plugin isn't available, the value of the
519
+ # configuration option @@all_fields_required_by_default is used.
520
+ #
521
+ def method_required?(attribute) #:nodoc:
522
+ if @object && @object.class.respond_to?(:reflect_on_validations_for)
523
+ attribute_sym = attribute.to_s.sub(/_id$/, '').to_sym
524
+
525
+ @object.class.reflect_on_validations_for(attribute_sym).any? do |validation|
526
+ validation.macro == :validates_presence_of &&
527
+ validation.name == attribute_sym &&
528
+ (validation.options.present? ? options_require_validation?(validation.options) : true)
529
+ end
530
+ else
531
+ @@all_fields_required_by_default
532
+ end
533
+ end
534
+
535
+ # Determines whether the given options evaluate to true
536
+ def options_require_validation?(options) #nodoc
537
+ if_condition = !options[:if].nil?
538
+ condition = if_condition ? options[:if] : options[:unless]
539
+
540
+ condition = if condition.respond_to?(:call)
541
+ condition.call(@object)
542
+ elsif condition.is_a?(::Symbol) && @object.respond_to?(condition)
543
+ @object.send(condition)
544
+ else
545
+ condition
546
+ end
547
+
548
+ if_condition ? !!condition : !condition
549
+ end
550
+
551
+ def basic_input_helper(form_helper_method, type, method, options) #:nodoc:
552
+ html_options = options.delete(:input_html) || {}
553
+ html_options = default_string_options(method, type).merge(html_options) if [:numeric, :string, :password, :text].include?(type)
554
+
555
+ self.label(method, options_for_label(options)) <<
556
+ self.send(form_helper_method, method, html_options)
557
+ end
558
+
559
+ # Outputs a label and standard Rails text field inside the wrapper.
560
+ def string_input(method, options)
561
+ basic_input_helper(:text_field, :string, method, options)
562
+ end
563
+
564
+ # Outputs a label and standard Rails password field inside the wrapper.
565
+ def password_input(method, options)
566
+ basic_input_helper(:password_field, :password, method, options)
567
+ end
568
+
569
+ # Outputs a label and standard Rails text field inside the wrapper.
570
+ def numeric_input(method, options)
571
+ basic_input_helper(:text_field, :numeric, method, options)
572
+ end
573
+
574
+ # Ouputs a label and standard Rails text area inside the wrapper.
575
+ def text_input(method, options)
576
+ basic_input_helper(:text_area, :text, method, options)
577
+ end
578
+
579
+ # Outputs a label and a standard Rails file field inside the wrapper.
580
+ def file_input(method, options)
581
+ basic_input_helper(:file_field, :file, method, options)
582
+ end
583
+
584
+ # Outputs a hidden field inside the wrapper, which should be hidden with CSS.
585
+ # Additionals options can be given and will be sent straight to hidden input
586
+ # element.
587
+ #
588
+ def hidden_input(method, options)
589
+ options ||= {}
590
+ if options[:input_html].present?
591
+ options[:value] = options[:input_html][:value] if options[:input_html][:value].present?
592
+ end
593
+ self.hidden_field(method, strip_formtastic_options(options))
594
+ end
595
+
596
+ # Outputs a label and a select box containing options from the parent
597
+ # (belongs_to, has_many, has_and_belongs_to_many) association. If an association
598
+ # is has_many or has_and_belongs_to_many the select box will be set as multi-select
599
+ # and size = 5
600
+ #
601
+ # Example (belongs_to):
602
+ #
603
+ # f.input :author
604
+ #
605
+ # <label for="book_author_id">Author</label>
606
+ # <select id="book_author_id" name="book[author_id]">
607
+ # <option value=""></option>
608
+ # <option value="1">Justin French</option>
609
+ # <option value="2">Jane Doe</option>
610
+ # </select>
611
+ #
612
+ # Example (has_many):
613
+ #
614
+ # f.input :chapters
615
+ #
616
+ # <label for="book_chapter_ids">Chapters</label>
617
+ # <select id="book_chapter_ids" name="book[chapter_ids]">
618
+ # <option value=""></option>
619
+ # <option value="1">Chapter 1</option>
620
+ # <option value="2">Chapter 2</option>
621
+ # </select>
622
+ #
623
+ # Example (has_and_belongs_to_many):
624
+ #
625
+ # f.input :authors
626
+ #
627
+ # <label for="book_author_ids">Authors</label>
628
+ # <select id="book_author_ids" name="book[author_ids]">
629
+ # <option value=""></option>
630
+ # <option value="1">Justin French</option>
631
+ # <option value="2">Jane Doe</option>
632
+ # </select>
633
+ #
634
+ #
635
+ # You can customize the options available in the select by passing in a collection (an Array or
636
+ # Hash) through the :collection option. If not provided, the choices are found by inferring the
637
+ # parent's class name from the method name and simply calling find(:all) on it
638
+ # (VehicleOwner.find(:all) in the example above).
639
+ #
640
+ # Examples:
641
+ #
642
+ # f.input :author, :collection => @authors
643
+ # f.input :author, :collection => Author.find(:all)
644
+ # f.input :author, :collection => [@justin, @kate]
645
+ # f.input :author, :collection => {@justin.name => @justin.id, @kate.name => @kate.id}
646
+ # f.input :author, :collection => ["Justin", "Kate", "Amelia", "Gus", "Meg"]
647
+ #
648
+ # The :label_method option allows you to customize the text label inside each option tag two ways:
649
+ #
650
+ # * by naming the correct method to call on each object in the collection as a symbol (:name, :login, etc)
651
+ # * by passing a Proc that will be called on each object in the collection, allowing you to use helpers or multiple model attributes together
652
+ #
653
+ # Examples:
654
+ #
655
+ # f.input :author, :label_method => :full_name
656
+ # f.input :author, :label_method => :login
657
+ # f.input :author, :label_method => :full_name_with_post_count
658
+ # f.input :author, :label_method => Proc.new { |a| "#{a.name} (#{pluralize("post", a.posts.count)})" }
659
+ #
660
+ # The :value_method option provides the same customization of the value attribute of each option tag.
661
+ #
662
+ # Examples:
663
+ #
664
+ # f.input :author, :value_method => :full_name
665
+ # f.input :author, :value_method => :login
666
+ # f.input :author, :value_method => Proc.new { |a| "author_#{a.login}" }
667
+ #
668
+ # You can pre-select a specific option value by passing in the :selected option.
669
+ #
670
+ # Examples:
671
+ #
672
+ # f.input :author, :selected => current_user.id
673
+ # f.input :author, :value_method => :login, :selected => current_user.login
674
+ # f.input :authors, :value_method => :login, :selected => Author.most_popular.collect(&:id)
675
+ # f.input :authors, :value_method => :login, :selected => nil # override any defaults: select none
676
+ #
677
+ # You can pass html_options to the select tag using :input_html => {}
678
+ #
679
+ # Examples:
680
+ #
681
+ # f.input :authors, :input_html => {:size => 20, :multiple => true}
682
+ #
683
+ # By default, all select inputs will have a blank option at the top of the list. You can add
684
+ # a prompt with the :prompt option, or disable the blank option with :include_blank => false.
685
+ #
686
+ #
687
+ # You can group the options in optgroup elements by passing the :group_by option
688
+ # (Note: only tested for belongs_to relations)
689
+ #
690
+ # Examples:
691
+ #
692
+ # f.input :author, :group_by => :continent
693
+ #
694
+ # All the other options should work as expected. If you want to call a custom method on the
695
+ # group item. You can include the option:group_label_method
696
+ # Examples:
697
+ #
698
+ # f.input :author, :group_by => :continents, :group_label_method => :something_different
699
+ #
700
+ def select_input(method, options)
701
+ html_options = options.delete(:input_html) || {}
702
+ options = set_include_blank(options)
703
+ html_options[:multiple] = html_options[:multiple] || options.delete(:multiple)
704
+ html_options.delete(:multiple) if html_options[:multiple].nil?
705
+
706
+ reflection = self.reflection_for(method)
707
+ if reflection && [ :has_many, :has_and_belongs_to_many ].include?(reflection.macro)
708
+ options[:include_blank] = false
709
+ html_options[:multiple] = true if html_options[:multiple].nil?
710
+ html_options[:size] ||= 5
711
+ end
712
+ options[:selected] = options[:selected].first if options[:selected].present? && html_options[:multiple] == false
713
+ input_name = generate_association_input_name(method)
714
+
715
+ select_html = if options[:group_by]
716
+ # The grouped_options_select is a bit counter intuitive and not optimised (mostly due to ActiveRecord).
717
+ # The formtastic user however shouldn't notice this too much.
718
+ raw_collection = find_raw_collection_for_column(method, options.reverse_merge(:find_options => { :include => options[:group_by] }))
719
+ label, value = detect_label_and_value_method!(raw_collection)
720
+ group_collection = raw_collection.map { |option| option.send(options[:group_by]) }.uniq
721
+ group_label_method = options[:group_label_method] || detect_label_method(group_collection)
722
+ group_collection = group_collection.sort_by { |group_item| group_item.send(group_label_method) }
723
+ group_association = options[:group_association] || detect_group_association(method, options[:group_by])
724
+
725
+ # Here comes the monster with 8 arguments
726
+ self.grouped_collection_select(input_name, group_collection,
727
+ group_association, group_label_method,
728
+ value, label,
729
+ strip_formtastic_options(options), html_options)
730
+ else
731
+ collection = find_collection_for_column(method, options)
732
+
733
+ self.select(input_name, collection, strip_formtastic_options(options), html_options)
734
+ end
735
+
736
+ self.label(method, options_for_label(options).merge(:input_name => input_name)) << select_html
737
+ end
738
+ alias :boolean_select_input :select_input
739
+
740
+ # Outputs a timezone select input as Rails' time_zone_select helper. You
741
+ # can give priority zones as option.
742
+ #
743
+ # Examples:
744
+ #
745
+ # f.input :time_zone, :as => :time_zone, :priority_zones => /Australia/
746
+ #
747
+ # You can pre-select a specific option value by passing in the :selected option.
748
+ # Note: Right now only works if the form object attribute value is not set (nil),
749
+ # because of how the core helper is implemented.
750
+ #
751
+ # Examples:
752
+ #
753
+ # f.input :my_favorite_time_zone, :as => :time_zone, :selected => 'Singapore'
754
+ #
755
+ def time_zone_input(method, options)
756
+ html_options = options.delete(:input_html) || {}
757
+ selected_value = options.delete(:selected)
758
+
759
+ self.label(method, options_for_label(options)) <<
760
+ self.time_zone_select(method, options.delete(:priority_zones),
761
+ strip_formtastic_options(options).merge(:default => selected_value), html_options)
762
+ end
763
+
764
+ # Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list
765
+ # items, one for each possible choice in the belongs_to association. Each li contains a
766
+ # label and a radio input.
767
+ #
768
+ # Example:
769
+ #
770
+ # f.input :author, :as => :radio
771
+ #
772
+ # Output:
773
+ #
774
+ # <fieldset>
775
+ # <legend><span>Author</span></legend>
776
+ # <ol>
777
+ # <li>
778
+ # <label for="book_author_id_1"><input id="book_author_id_1" name="book[author_id]" type="radio" value="1" /> Justin French</label>
779
+ # </li>
780
+ # <li>
781
+ # <label for="book_author_id_2"><input id="book_author_id_2" name="book[owner_id]" type="radio" value="2" /> Kate French</label>
782
+ # </li>
783
+ # </ol>
784
+ # </fieldset>
785
+ #
786
+ # You can customize the choices available in the radio button set by passing in a collection (an Array or
787
+ # Hash) through the :collection option. If not provided, the choices are found by reflecting on the association
788
+ # (Author.find(:all) in the example above).
789
+ #
790
+ # Examples:
791
+ #
792
+ # f.input :author, :as => :radio, :collection => @authors
793
+ # f.input :author, :as => :radio, :collection => Author.find(:all)
794
+ # f.input :author, :as => :radio, :collection => [@justin, @kate]
795
+ # f.input :author, :collection => ["Justin", "Kate", "Amelia", "Gus", "Meg"]
796
+ #
797
+ # The :label_method option allows you to customize the label for each radio button two ways:
798
+ #
799
+ # * by naming the correct method to call on each object in the collection as a symbol (:name, :login, etc)
800
+ # * by passing a Proc that will be called on each object in the collection, allowing you to use helpers or multiple model attributes together
801
+ #
802
+ # Examples:
803
+ #
804
+ # f.input :author, :as => :radio, :label_method => :full_name
805
+ # f.input :author, :as => :radio, :label_method => :login
806
+ # f.input :author, :as => :radio, :label_method => :full_name_with_post_count
807
+ # f.input :author, :as => :radio, :label_method => Proc.new { |a| "#{a.name} (#{pluralize("post", a.posts.count)})" }
808
+ #
809
+ # The :value_method option provides the same customization of the value attribute of each option tag.
810
+ #
811
+ # Examples:
812
+ #
813
+ # f.input :author, :as => :radio, :value_method => :full_name
814
+ # f.input :author, :as => :radio, :value_method => :login
815
+ # f.input :author, :as => :radio, :value_method => Proc.new { |a| "author_#{a.login}" }
816
+ #
817
+ # You can force a particular radio button in the collection to be checked with the :selected option.
818
+ #
819
+ # Examples:
820
+ #
821
+ # f.input :subscribe_to_newsletter, :as => :radio, :selected => true
822
+ # f.input :subscribe_to_newsletter, :as => :radio, :collection => ["Yeah!", "Nope!"], :selected => "Nope!"
823
+ #
824
+ # Finally, you can set :value_as_class => true if you want the li wrapper around each radio
825
+ # button / label combination to contain a class with the value of the radio button (useful for
826
+ # applying specific CSS or Javascript to a particular radio button).
827
+ #
828
+ def radio_input(method, options)
829
+ collection = find_collection_for_column(method, options)
830
+ html_options = strip_formtastic_options(options).merge(options.delete(:input_html) || {})
831
+
832
+ input_name = generate_association_input_name(method)
833
+ value_as_class = options.delete(:value_as_class)
834
+ input_ids = []
835
+ selected_option_is_present = [:selected, :checked].any? { |k| options.key?(k) }
836
+ selected_value = (options.key?(:checked) ? options[:checked] : options[:selected]) if selected_option_is_present
837
+
838
+ list_item_content = collection.map do |c|
839
+ label = c.is_a?(Array) ? c.first : c
840
+ value = c.is_a?(Array) ? c.last : c
841
+ input_id = generate_html_id(input_name, value.to_s.gsub(/\s/, '_').gsub(/\W/, '').downcase)
842
+ input_ids << input_id
843
+
844
+ html_options[:checked] = selected_value == value if selected_option_is_present
845
+
846
+ li_content = template.content_tag(:label,
847
+ "#{self.radio_button(input_name, value, html_options)} #{label}",
848
+ :for => input_id
849
+ )
850
+
851
+ li_options = value_as_class ? { :class => [method.to_s.singularize, value.to_s.downcase].join('_') } : {}
852
+ template.content_tag(:li, li_content, li_options)
853
+ end
854
+
855
+ field_set_and_list_wrapping_for_method(method, options.merge(:label_for => input_ids.first), list_item_content)
856
+ end
857
+ alias :boolean_radio_input :radio_input
858
+
859
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
860
+ # items (li), one for each fragment for the date (year, month, day). Each li contains a label
861
+ # (eg "Year") and a select box. See date_or_datetime_input for a more detailed output example.
862
+ #
863
+ # You can pre-select a specific option value by passing in the :selected option.
864
+ #
865
+ # Examples:
866
+ #
867
+ # f.input :created_at, :as => :date, :selected => 1.day.ago
868
+ # f.input :created_at, :as => :date, :selected => nil # override any defaults: select none
869
+ #
870
+ # Some of Rails' options for select_date are supported, but not everything yet, see
871
+ # documentation of date_or_datetime_input() for more information.
872
+ def date_input(method, options)
873
+ options = set_include_blank(options)
874
+ date_or_datetime_input(method, options.merge(:discard_hour => true))
875
+ end
876
+
877
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
878
+ # items (li), one for each fragment for the date (year, month, day, hour, min, sec). Each li
879
+ # contains a label (eg "Year") and a select box. See date_or_datetime_input for a more
880
+ # detailed output example.
881
+ #
882
+ # You can pre-select a specific option value by passing in the :selected option.
883
+ #
884
+ # Examples:
885
+ #
886
+ # f.input :created_at, :as => :datetime, :selected => 1.day.ago
887
+ # f.input :created_at, :as => :datetime, :selected => nil # override any defaults: select none
888
+ #
889
+ # Some of Rails' options for select_date are supported, but not everything yet, see
890
+ # documentation of date_or_datetime_input() for more information.
891
+ def datetime_input(method, options)
892
+ options = set_include_blank(options)
893
+ date_or_datetime_input(method, options)
894
+ end
895
+
896
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
897
+ # items (li), one for each fragment for the time (hour, minute, second). Each li contains a label
898
+ # (eg "Hour") and a select box. See date_or_datetime_input for a more detailed output example.
899
+ #
900
+ # You can pre-select a specific option value by passing in the :selected option.
901
+ #
902
+ # Examples:
903
+ #
904
+ # f.input :created_at, :as => :time, :selected => 1.hour.ago
905
+ # f.input :created_at, :as => :time, :selected => nil # override any defaults: select none
906
+ #
907
+ # Some of Rails' options for select_time are supported, but not everything yet, see
908
+ # documentation of date_or_datetime_input() for more information.
909
+ def time_input(method, options)
910
+ options = set_include_blank(options)
911
+ date_or_datetime_input(method, options.merge(:discard_year => true, :discard_month => true, :discard_day => true))
912
+ end
913
+
914
+ # Helper method used by :as => (:date|:datetime|:time). Generates a fieldset containing a
915
+ # legend (for what would normally be considered the label), and an ordered list of list items
916
+ # for year, month, day, hour, etc, each containing a label and a select. Example:
917
+ #
918
+ # <fieldset>
919
+ # <legend>Created At</legend>
920
+ # <ol>
921
+ # <li>
922
+ # <label for="user_created_at_1i">Year</label>
923
+ # <select id="user_created_at_1i" name="user[created_at(1i)]">
924
+ # <option value="2003">2003</option>
925
+ # ...
926
+ # <option value="2013">2013</option>
927
+ # </select>
928
+ # </li>
929
+ # <li>
930
+ # <label for="user_created_at_2i">Month</label>
931
+ # <select id="user_created_at_2i" name="user[created_at(2i)]">
932
+ # <option value="1">January</option>
933
+ # ...
934
+ # <option value="12">December</option>
935
+ # </select>
936
+ # </li>
937
+ # <li>
938
+ # <label for="user_created_at_3i">Day</label>
939
+ # <select id="user_created_at_3i" name="user[created_at(3i)]">
940
+ # <option value="1">1</option>
941
+ # ...
942
+ # <option value="31">31</option>
943
+ # </select>
944
+ # </li>
945
+ # </ol>
946
+ # </fieldset>
947
+ #
948
+ # This is an absolute abomination, but so is the official Rails select_date().
949
+ #
950
+ # Options:
951
+ #
952
+ # * @:order => [:month, :day, :year]@
953
+ # * @:include_seconds@ => true@
954
+ # * @:selected => Time.mktime(2008)@
955
+ # * @:selected => Date.new(2008)@
956
+ # * @:selected => nil@
957
+ # * @:discard_(year|month|day|hour|minute) => true@
958
+ # * @:include_blank => true@
959
+ def date_or_datetime_input(method, options)
960
+ position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
961
+ i18n_date_order = ::I18n.t(:order, :scope => [:date])
962
+ i18n_date_order = nil unless i18n_date_order.is_a?(Array)
963
+ inputs = options.delete(:order) || i18n_date_order || [:year, :month, :day]
964
+
965
+ time_inputs = [:hour, :minute]
966
+ time_inputs << [:second] if options[:include_seconds]
967
+
968
+ list_items_capture = ""
969
+ hidden_fields_capture = ""
970
+
971
+ default_time = options.has_key?(:selected) ? options[:selected] : ::Time.now
972
+
973
+ # Gets the datetime object. It can be a Fixnum, Date or Time, or nil.
974
+ datetime = options[:selected] || (@object ? @object.send(method) : default_time) || default_time
975
+
976
+ html_options = options.delete(:input_html) || {}
977
+ input_ids = []
978
+
979
+ (inputs + time_inputs).each do |input|
980
+ input_ids << input_id = generate_html_id(method, "#{position[input]}i")
981
+
982
+ field_name = "#{method}(#{position[input]}i)"
983
+ if options[:"discard_#{input}"]
984
+ break if time_inputs.include?(input)
985
+
986
+ hidden_value = datetime.respond_to?(input) ? datetime.send(input.to_sym) : datetime
987
+ hidden_fields_capture << template.hidden_field_tag("#{@object_name}[#{field_name}]", (hidden_value || 1), :id => input_id)
988
+ else
989
+ opts = strip_formtastic_options(options).merge(:prefix => @object_name, :field_name => field_name, :default => datetime)
990
+ item_label_text = ::I18n.t(input.to_s, :default => input.to_s.humanize, :scope => [:datetime, :prompts])
991
+
992
+ list_items_capture << template.content_tag(:li,
993
+ template.content_tag(:label, item_label_text, :for => input_id) <<
994
+ template.send(:"select_#{input}", datetime, opts, html_options.merge(:id => input_id))
995
+ )
996
+ end
997
+ end
998
+
999
+ hidden_fields_capture << field_set_and_list_wrapping_for_method(method, options.merge(:label_for => input_ids.first), list_items_capture)
1000
+ end
1001
+
1002
+ # Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list
1003
+ # items, one for each possible choice in the belongs_to association. Each li contains a
1004
+ # label and a check_box input.
1005
+ #
1006
+ # This is an alternative for has many and has and belongs to many associations.
1007
+ #
1008
+ # Example:
1009
+ #
1010
+ # f.input :author, :as => :check_boxes
1011
+ #
1012
+ # Output:
1013
+ #
1014
+ # <fieldset>
1015
+ # <legend class="label"><label>Authors</label></legend>
1016
+ # <ol>
1017
+ # <li>
1018
+ # <input type="hidden" name="book[author_id][1]" value="">
1019
+ # <label for="book_author_id_1"><input id="book_author_id_1" name="book[author_id][1]" type="checkbox" value="1" /> Justin French</label>
1020
+ # </li>
1021
+ # <li>
1022
+ # <input type="hidden" name="book[author_id][2]" value="">
1023
+ # <label for="book_author_id_2"><input id="book_author_id_2" name="book[owner_id][2]" type="checkbox" value="2" /> Kate French</label>
1024
+ # </li>
1025
+ # </ol>
1026
+ # </fieldset>
1027
+ #
1028
+ # Notice that the value of the checkbox is the same as the id and the hidden
1029
+ # field has empty value. You can override the hidden field value using the
1030
+ # unchecked_value option.
1031
+ #
1032
+ # You can customize the options available in the set by passing in a collection (Array) of
1033
+ # ActiveRecord objects through the :collection option. If not provided, the choices are found
1034
+ # by inferring the parent's class name from the method name and simply calling find(:all) on
1035
+ # it (Author.find(:all) in the example above).
1036
+ #
1037
+ # Examples:
1038
+ #
1039
+ # f.input :author, :as => :check_boxes, :collection => @authors
1040
+ # f.input :author, :as => :check_boxes, :collection => Author.find(:all)
1041
+ # f.input :author, :as => :check_boxes, :collection => [@justin, @kate]
1042
+ #
1043
+ # The :label_method option allows you to customize the label for each checkbox two ways:
1044
+ #
1045
+ # * by naming the correct method to call on each object in the collection as a symbol (:name, :login, etc)
1046
+ # * by passing a Proc that will be called on each object in the collection, allowing you to use helpers or multiple model attributes together
1047
+ #
1048
+ # Examples:
1049
+ #
1050
+ # f.input :author, :as => :check_boxes, :label_method => :full_name
1051
+ # f.input :author, :as => :check_boxes, :label_method => :login
1052
+ # f.input :author, :as => :check_boxes, :label_method => :full_name_with_post_count
1053
+ # f.input :author, :as => :check_boxes, :label_method => Proc.new { |a| "#{a.name} (#{pluralize("post", a.posts.count)})" }
1054
+ #
1055
+ # The :value_method option provides the same customization of the value attribute of each checkbox input tag.
1056
+ #
1057
+ # Examples:
1058
+ #
1059
+ # f.input :author, :as => :check_boxes, :value_method => :full_name
1060
+ # f.input :author, :as => :check_boxes, :value_method => :login
1061
+ # f.input :author, :as => :check_boxes, :value_method => Proc.new { |a| "author_#{a.login}" }
1062
+ #
1063
+ # You can pre-select/check a specific checkbox value by passing in the :selected option (alias :checked works as well).
1064
+ #
1065
+ # Examples:
1066
+ #
1067
+ # f.input :authors, :as => :check_boxes, :selected => @justin
1068
+ # f.input :authors, :as => :check_boxes, :selected => Author.most_popular.collect(&:id)
1069
+ # f.input :authors, :as => :check_boxes, :selected => nil # override any defaults: select none
1070
+ #
1071
+ # Finally, you can set :value_as_class => true if you want the li wrapper around each checkbox / label
1072
+ # combination to contain a class with the value of the radio button (useful for applying specific
1073
+ # CSS or Javascript to a particular checkbox).
1074
+ #
1075
+ def check_boxes_input(method, options)
1076
+ collection = find_collection_for_column(method, options)
1077
+ html_options = options.delete(:input_html) || {}
1078
+
1079
+ input_name = generate_association_input_name(method)
1080
+ value_as_class = options.delete(:value_as_class)
1081
+ unchecked_value = options.delete(:unchecked_value) || ''
1082
+ html_options = { :name => "#{@object_name}[#{input_name}][]" }.merge(html_options)
1083
+ input_ids = []
1084
+
1085
+ selected_option_is_present = [:selected, :checked].any? { |k| options.key?(k) }
1086
+ selected_values = (options.key?(:checked) ? options[:checked] : options[:selected]) if selected_option_is_present
1087
+ selected_values = [*selected_values].compact
1088
+
1089
+ list_item_content = collection.map do |c|
1090
+ label = c.is_a?(Array) ? c.first : c
1091
+ value = c.is_a?(Array) ? c.last : c
1092
+ input_id = generate_html_id(input_name, value.to_s.gsub(/\s/, '_').gsub(/\W/, '').downcase)
1093
+ input_ids << input_id
1094
+
1095
+ html_options[:checked] = selected_values.include?(value) if selected_option_is_present
1096
+ html_options[:id] = input_id
1097
+
1098
+ li_content = template.content_tag(:label,
1099
+ "#{self.check_box(input_name, html_options, value, unchecked_value)} #{label}",
1100
+ :for => input_id
1101
+ )
1102
+
1103
+ li_options = value_as_class ? { :class => [method.to_s.singularize, value.to_s.downcase].join('_') } : {}
1104
+ template.content_tag(:li, li_content, li_options)
1105
+ end
1106
+
1107
+ field_set_and_list_wrapping_for_method(method, options.merge(:label_for => input_ids.first), list_item_content)
1108
+ end
1109
+
1110
+ # Outputs a country select input, wrapping around a regular country_select helper.
1111
+ # Rails doesn't come with a country_select helper by default any more, so you'll need to install
1112
+ # the "official" plugin, or, if you wish, any other country_select plugin that behaves in the
1113
+ # same way.
1114
+ #
1115
+ # The Rails plugin iso-3166-country-select plugin can be found "here":http://github.com/rails/iso-3166-country-select.
1116
+ #
1117
+ # By default, Formtastic includes a handfull of english-speaking countries as "priority counties",
1118
+ # which you can change to suit your market and user base (see README for more info on config).
1119
+ #
1120
+ # Examples:
1121
+ # f.input :location, :as => :country # use Formtastic::SemanticFormBuilder.priority_countries array for the priority countries
1122
+ # f.input :location, :as => :country, :priority_countries => /Australia/ # set your own
1123
+ #
1124
+ def country_input(method, options)
1125
+ 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)
1126
+
1127
+ html_options = options.delete(:input_html) || {}
1128
+ priority_countries = options.delete(:priority_countries) || @@priority_countries
1129
+
1130
+ self.label(method, options_for_label(options)) <<
1131
+ self.country_select(method, priority_countries, strip_formtastic_options(options), html_options)
1132
+ end
1133
+
1134
+ # Outputs a label containing a checkbox and the label text. The label defaults
1135
+ # to the column name (method name) and can be altered with the :label option.
1136
+ # :checked_value and :unchecked_value options are also available.
1137
+ #
1138
+ # You can pre-select/check the boolean checkbox by passing in the :selected option (alias :checked works as well).
1139
+ #
1140
+ # Examples:
1141
+ #
1142
+ # f.input :allow_comments, :as => :boolean, :selected => true # override any default value: selected/checked
1143
+ #
1144
+ def boolean_input(method, options)
1145
+ html_options = options.delete(:input_html) || {}
1146
+ checked = options.key?(:checked) ? options[:checked] : options[:selected]
1147
+ html_options[:checked] = checked == true if [:selected, :checked].any? { |k| options.key?(k) }
1148
+
1149
+ input = self.check_box(method, strip_formtastic_options(options).merge(html_options),
1150
+ options.delete(:checked_value) || '1', options.delete(:unchecked_value) || '0')
1151
+ options = options_for_label(options)
1152
+
1153
+ # the label() method will insert this nested input into the label at the last minute
1154
+ options[:label_prefix_for_nested_input] = input
1155
+
1156
+ self.label(method, options)
1157
+ end
1158
+
1159
+ # Generates an input for the given method using the type supplied with :as.
1160
+ def inline_input_for(method, options)
1161
+ send(:"#{options.delete(:as)}_input", method, options)
1162
+ end
1163
+
1164
+ # Generates hints for the given method using the text supplied in :hint.
1165
+ #
1166
+ def inline_hints_for(method, options) #:nodoc:
1167
+ options[:hint] = localized_string(method, options[:hint], :hint)
1168
+ return if options[:hint].blank?
1169
+ template.content_tag(:p, options[:hint], :class => 'inline-hints')
1170
+ end
1171
+
1172
+ # Creates an error sentence by calling to_sentence on the errors array.
1173
+ #
1174
+ def error_sentence(errors) #:nodoc:
1175
+ template.content_tag(:p, errors.to_sentence.untaint, :class => 'inline-errors')
1176
+ end
1177
+
1178
+ # Creates an error li list.
1179
+ #
1180
+ def error_list(errors) #:nodoc:
1181
+ list_elements = []
1182
+ errors.each do |error|
1183
+ list_elements << template.content_tag(:li, error.untaint)
1184
+ end
1185
+ template.content_tag(:ul, list_elements.join("\n"), :class => 'errors')
1186
+ end
1187
+
1188
+ # Creates an error sentence containing only the first error
1189
+ #
1190
+ def error_first(errors) #:nodoc:
1191
+ template.content_tag(:p, errors.first.untaint, :class => 'inline-errors')
1192
+ end
1193
+
1194
+ # Generates the required or optional string. If the value set is a proc,
1195
+ # it evaluates the proc first.
1196
+ #
1197
+ def required_or_optional_string(required) #:nodoc:
1198
+ string_or_proc = case required
1199
+ when true
1200
+ @@required_string
1201
+ when false
1202
+ @@optional_string
1203
+ else
1204
+ required
1205
+ end
1206
+
1207
+ if string_or_proc.is_a?(Proc)
1208
+ string_or_proc.call
1209
+ else
1210
+ string_or_proc.to_s
1211
+ end
1212
+ end
1213
+
1214
+ # Generates a fieldset and wraps the content in an ordered list. When working
1215
+ # with nested attributes (in Rails 2.3), it allows %i as interpolation option
1216
+ # in :name. So you can do:
1217
+ #
1218
+ # f.inputs :name => 'Task #%i', :for => :tasks
1219
+ #
1220
+ # or the shorter equivalent:
1221
+ #
1222
+ # f.inputs 'Task #%i', :for => :tasks
1223
+ #
1224
+ # And it will generate a fieldset for each task with legend 'Task #1', 'Task #2',
1225
+ # 'Task #3' and so on.
1226
+ #
1227
+ # Note: Special case for the inline inputs (non-block):
1228
+ # f.inputs "My little legend", :title, :body, :author # Explicit legend string => "My little legend"
1229
+ # f.inputs :my_little_legend, :title, :body, :author # Localized (118n) legend with I18n key => I18n.t(:my_little_legend, ...)
1230
+ # f.inputs :title, :body, :author # First argument is a column => (no legend)
1231
+ #
1232
+ def field_set_and_list_wrapping(*args, &block) #:nodoc:
1233
+ contents = args.last.is_a?(::Hash) ? '' : args.pop.flatten
1234
+ html_options = args.extract_options!
1235
+
1236
+ legend = html_options.delete(:name).to_s
1237
+ legend %= parent_child_index(html_options[:parent]) if html_options[:parent]
1238
+ legend = template.content_tag(:legend, template.content_tag(:span, legend)) unless legend.blank?
1239
+
1240
+ if block_given?
1241
+ contents = if template.respond_to?(:is_haml?) && template.is_haml?
1242
+ template.capture_haml(&block)
1243
+ else
1244
+ template.capture(&block)
1245
+ end
1246
+ end
1247
+
1248
+ # Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
1249
+ contents = contents.join if contents.respond_to?(:join)
1250
+ fieldset = template.content_tag(:fieldset,
1251
+ legend << template.content_tag(:ol, contents),
1252
+ html_options.except(:builder, :parent)
1253
+ )
1254
+
1255
+ template.concat(fieldset) if block_given?
1256
+ fieldset
1257
+ end
1258
+
1259
+ def field_set_title_from_args(*args) #:nodoc:
1260
+ options = args.extract_options!
1261
+ options[:name] ||= options.delete(:title)
1262
+ title = options[:name]
1263
+
1264
+ if title.blank?
1265
+ valid_name_classes = [::String, ::Symbol]
1266
+ valid_name_classes.delete(::Symbol) if !block_given? && (args.first.is_a?(::Symbol) && self.content_columns.include?(args.first))
1267
+ title = args.shift if valid_name_classes.any? { |valid_name_class| args.first.is_a?(valid_name_class) }
1268
+ end
1269
+ title = localized_string(title, title, :title) if title.is_a?(::Symbol)
1270
+ title
1271
+ end
1272
+
1273
+ # Also generates a fieldset and an ordered list but with label based in
1274
+ # method. This methods is currently used by radio and datetime inputs.
1275
+ #
1276
+ def field_set_and_list_wrapping_for_method(method, options, contents) #:nodoc:
1277
+ contents = contents.join if contents.respond_to?(:join)
1278
+
1279
+ template.content_tag(:fieldset,
1280
+ template.content_tag(:legend,
1281
+ self.label(method, options_for_label(options).merge(:for => options.delete(:label_for))), :class => 'label'
1282
+ ) <<
1283
+ template.content_tag(:ol, contents)
1284
+ )
1285
+ end
1286
+
1287
+ # For methods that have a database column, take a best guess as to what the input method
1288
+ # should be. In most cases, it will just return the column type (eg :string), but for special
1289
+ # cases it will simplify (like the case of :integer, :float & :decimal to :numeric), or do
1290
+ # something different (like :password and :select).
1291
+ #
1292
+ # If there is no column for the method (eg "virtual columns" with an attr_accessor), the
1293
+ # default is a :string, a similar behaviour to Rails' scaffolding.
1294
+ #
1295
+ def default_input_type(method, options = {}) #:nodoc:
1296
+ if column = self.column_for(method)
1297
+ # Special cases where the column type doesn't map to an input method.
1298
+ case column.type
1299
+ when :string
1300
+ return :password if method.to_s =~ /password/
1301
+ return :country if method.to_s =~ /country/
1302
+ return :time_zone if method.to_s =~ /time_zone/
1303
+ when :integer
1304
+ return :select if method.to_s =~ /_id$/
1305
+ return :numeric
1306
+ when :float, :decimal
1307
+ return :numeric
1308
+ when :timestamp
1309
+ return :datetime
1310
+ end
1311
+
1312
+ # Try look for hints in options hash. Quite common senario: Enum keys stored as string in the database.
1313
+ return :select if column.type == :string && options.key?(:collection)
1314
+ # Try 3: Assume the input name will be the same as the column type (e.g. string_input).
1315
+ return column.type
1316
+ else
1317
+ if @object
1318
+ return :select if self.reflection_for(method)
1319
+
1320
+ file = @object.send(method) if @object.respond_to?(method)
1321
+ return :file if file && @@file_methods.any? { |m| file.respond_to?(m) }
1322
+ end
1323
+
1324
+ return :select if options.key?(:collection)
1325
+ return :password if method.to_s =~ /password/
1326
+ return :string
1327
+ end
1328
+ end
1329
+
1330
+ # Used by select and radio inputs. The collection can be retrieved by
1331
+ # three ways:
1332
+ #
1333
+ # * Explicitly provided through :collection
1334
+ # * Retrivied through an association
1335
+ # * Or a boolean column, which will generate a localized { "Yes" => true, "No" => false } hash.
1336
+ #
1337
+ # If the collection is not a hash or an array of strings, fixnums or arrays,
1338
+ # we use label_method and value_method to retreive an array with the
1339
+ # appropriate label and value.
1340
+ #
1341
+ def find_collection_for_column(column, options) #:nodoc:
1342
+ collection = find_raw_collection_for_column(column, options)
1343
+
1344
+ # Return if we have an Array of strings, fixnums or arrays
1345
+ return collection if (collection.instance_of?(Array) || collection.instance_of?(Range)) &&
1346
+ [Array, Fixnum, String, Symbol].include?(collection.first.class)
1347
+
1348
+ label, value = detect_label_and_value_method!(collection, options)
1349
+ collection.map { |o| [send_or_call(label, o), send_or_call(value, o)] }
1350
+ end
1351
+
1352
+ # As #find_collection_for_column but returns the collection without mapping the label and value
1353
+ #
1354
+ def find_raw_collection_for_column(column, options) #:nodoc:
1355
+ collection = if options[:collection]
1356
+ options.delete(:collection)
1357
+ elsif reflection = self.reflection_for(column)
1358
+ reflection.klass.find(:all, options[:find_options] || {})
1359
+ else
1360
+ create_boolean_collection(options)
1361
+ end
1362
+
1363
+ collection = collection.to_a if collection.is_a?(Hash)
1364
+ collection
1365
+ end
1366
+
1367
+ # Detects the label and value methods from a collection values set in
1368
+ # @@collection_label_methods. It will use and delete
1369
+ # the options :label_method and :value_methods when present
1370
+ #
1371
+ def detect_label_and_value_method!(collection_or_instance, options = {}) #:nodoc
1372
+ label = options.delete(:label_method) || detect_label_method(collection_or_instance)
1373
+ value = options.delete(:value_method) || :id
1374
+ [label, value]
1375
+ end
1376
+
1377
+ # Detected the label collection method when none is supplied using the
1378
+ # values set in @@collection_label_methods.
1379
+ #
1380
+ def detect_label_method(collection) #:nodoc:
1381
+ @@collection_label_methods.detect { |m| collection.first.respond_to?(m) }
1382
+ end
1383
+
1384
+ # Detects the method to call for fetching group members from the groups when grouping select options
1385
+ #
1386
+ def detect_group_association(method, group_by)
1387
+ object_to_method_reflection = self.reflection_for(method)
1388
+ method_class = object_to_method_reflection.klass
1389
+
1390
+ method_to_group_association = method_class.reflect_on_association(group_by)
1391
+ group_class = method_to_group_association.klass
1392
+
1393
+ # This will return in the normal case
1394
+ return method.to_s.pluralize.to_sym if group_class.reflect_on_association(method.to_s.pluralize)
1395
+
1396
+ # This is for belongs_to associations named differently than their class
1397
+ # form.input :parent, :group_by => :customer
1398
+ # eg.
1399
+ # class Project
1400
+ # belongs_to :parent, :class_name => 'Project', :foreign_key => 'parent_id'
1401
+ # belongs_to :customer
1402
+ # end
1403
+ # class Customer
1404
+ # has_many :projects
1405
+ # end
1406
+ group_method = method_class.to_s.underscore.pluralize.to_sym
1407
+ return group_method if group_class.reflect_on_association(group_method) # :projects
1408
+
1409
+ # This is for has_many associations named differently than their class
1410
+ # eg.
1411
+ # class Project
1412
+ # belongs_to :parent, :class_name => 'Project', :foreign_key => 'parent_id'
1413
+ # belongs_to :customer
1414
+ # end
1415
+ # class Customer
1416
+ # has_many :tasks, :class_name => 'Project', :foreign_key => 'customer_id'
1417
+ # end
1418
+ possible_associations = group_class.reflect_on_all_associations(:has_many).find_all{|assoc| assoc.klass == object_class}
1419
+ return possible_associations.first.name.to_sym if possible_associations.count == 1
1420
+
1421
+ raise "Cannot infer group association for #{method} grouped by #{group_by}, there were #{possible_associations.empty? ? 'no' : possible_associations.size} possible associations. Please specify using :group_association"
1422
+
1423
+ end
1424
+
1425
+ # Returns a hash to be used by radio and select inputs when a boolean field
1426
+ # is provided.
1427
+ #
1428
+ def create_boolean_collection(options) #:nodoc:
1429
+ options[:true] ||= ::Formtastic::I18n.t(:yes)
1430
+ options[:false] ||= ::Formtastic::I18n.t(:no)
1431
+ options[:value_as_class] = true unless options.key?(:value_as_class)
1432
+
1433
+ [ [ options.delete(:true), true], [ options.delete(:false), false ] ]
1434
+ end
1435
+
1436
+ # Used by association inputs (select, radio) to generate the name that should
1437
+ # be used for the input
1438
+ #
1439
+ # belongs_to :author; f.input :author; will generate 'author_id'
1440
+ # belongs_to :entity, :foreign_key = :owner_id; f.input :author; will generate 'owner_id'
1441
+ # has_many :authors; f.input :authors; will generate 'author_ids'
1442
+ # has_and_belongs_to_many will act like has_many
1443
+ #
1444
+ def generate_association_input_name(method) #:nodoc:
1445
+ if reflection = self.reflection_for(method)
1446
+ if [:has_and_belongs_to_many, :has_many].include?(reflection.macro)
1447
+ "#{method.to_s.singularize}_ids"
1448
+ else
1449
+ reflection.options[:foreign_key] || "#{method}_id"
1450
+ end
1451
+ else
1452
+ method
1453
+ end.to_sym
1454
+ end
1455
+
1456
+ # If an association method is passed in (f.input :author) try to find the
1457
+ # reflection object.
1458
+ #
1459
+ def reflection_for(method) #:nodoc:
1460
+ @object.class.reflect_on_association(method) if @object.class.respond_to?(:reflect_on_association)
1461
+ end
1462
+
1463
+ # Get a column object for a specified attribute method - if possible.
1464
+ #
1465
+ def column_for(method) #:nodoc:
1466
+ @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute)
1467
+ end
1468
+
1469
+ # Generates default_string_options by retrieving column information from
1470
+ # the database.
1471
+ #
1472
+ def default_string_options(method, type) #:nodoc:
1473
+ column = self.column_for(method)
1474
+
1475
+ if type == :text
1476
+ { :cols => @@default_text_field_size, :rows => @@default_text_area_height }
1477
+ elsif type == :numeric || column.nil? || column.limit.nil?
1478
+ { :size => @@default_text_field_size }
1479
+ else
1480
+ { :maxlength => column.limit, :size => [column.limit, @@default_text_field_size].min }
1481
+ end
1482
+ end
1483
+
1484
+ # Generate the html id for the li tag.
1485
+ # It takes into account options[:index] and @auto_index to generate li
1486
+ # elements with appropriate index scope. It also sanitizes the object
1487
+ # and method names.
1488
+ #
1489
+ def generate_html_id(method_name, value='input') #:nodoc:
1490
+ if options.has_key?(:index)
1491
+ index = "_#{options[:index]}"
1492
+ elsif defined?(@auto_index)
1493
+ index = "_#{@auto_index}"
1494
+ else
1495
+ index = ""
1496
+ end
1497
+ sanitized_method_name = method_name.to_s.gsub(/[\?\/\-]$/, '')
1498
+
1499
+ "#{sanitized_object_name}#{index}_#{sanitized_method_name}_#{value}"
1500
+ end
1501
+
1502
+ # Gets the nested_child_index value from the parent builder. In Rails 2.3
1503
+ # it always returns a fixnum. In next versions it returns a hash with each
1504
+ # association that the parent builds.
1505
+ #
1506
+ def parent_child_index(parent) #:nodoc:
1507
+ duck = parent[:builder].instance_variable_get('@nested_child_index')
1508
+
1509
+ if duck.is_a?(Hash)
1510
+ child = parent[:for]
1511
+ child = child.first if child.respond_to?(:first)
1512
+ duck[child].to_i + 1
1513
+ else
1514
+ duck.to_i + 1
1515
+ end
1516
+ end
1517
+
1518
+ def sanitized_object_name #:nodoc:
1519
+ @sanitized_object_name ||= @object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
1520
+ end
1521
+
1522
+ def humanized_attribute_name(method) #:nodoc:
1523
+ if @object && @object.class.respond_to?(:human_attribute_name)
1524
+ humanized_name = @object.class.human_attribute_name(method.to_s)
1525
+ if humanized_name == method.to_s.send(:humanize)
1526
+ method.to_s.send(@@label_str_method)
1527
+ else
1528
+ humanized_name
1529
+ end
1530
+ else
1531
+ method.to_s.send(@@label_str_method)
1532
+ end
1533
+ end
1534
+
1535
+ # Internal generic method for looking up localized values within Formtastic
1536
+ # using I18n, if no explicit value is set and I18n-lookups are enabled.
1537
+ #
1538
+ # Enabled/Disable this by setting:
1539
+ #
1540
+ # Formtastic::SemanticFormBuilder.i18n_lookups_by_default = true/false
1541
+ #
1542
+ # Lookup priority:
1543
+ #
1544
+ # 'formtastic.{{type}}.{{model}}.{{action}}.{{attribute}}'
1545
+ # 'formtastic.{{type}}.{{model}}.{{attribute}}'
1546
+ # 'formtastic.{{type}}.{{attribute}}'
1547
+ #
1548
+ # Example:
1549
+ #
1550
+ # 'formtastic.labels.post.edit.title'
1551
+ # 'formtastic.labels.post.title'
1552
+ # 'formtastic.labels.title'
1553
+ #
1554
+ # NOTE: Generic, but only used for form input titles/labels/hints/actions (titles = legends, actions = buttons).
1555
+ #
1556
+ def localized_string(key, value, type, options = {}) #:nodoc:
1557
+ key = value if value.is_a?(::Symbol)
1558
+
1559
+ if value.is_a?(::String)
1560
+ value
1561
+ else
1562
+ use_i18n = value.nil? ? @@i18n_lookups_by_default : (value != false)
1563
+
1564
+ if use_i18n
1565
+ model_name = self.model_name.underscore
1566
+ action_name = template.params[:action].to_s rescue ''
1567
+ attribute_name = key.to_s
1568
+
1569
+ defaults = ::Formtastic::I18n::SCOPES.collect do |i18n_scope|
1570
+ i18n_path = i18n_scope.dup
1571
+ i18n_path.gsub!('{{action}}', action_name)
1572
+ i18n_path.gsub!('{{model}}', model_name)
1573
+ i18n_path.gsub!('{{attribute}}', attribute_name)
1574
+ i18n_path.gsub!('..', '.')
1575
+ i18n_path.to_sym
1576
+ end
1577
+ defaults << ''
1578
+
1579
+ i18n_value = ::Formtastic::I18n.t(defaults.shift,
1580
+ options.merge(:default => defaults, :scope => type.to_s.pluralize.to_sym))
1581
+ i18n_value.blank? ? nil : i18n_value
1582
+ end
1583
+ end
1584
+ end
1585
+
1586
+ def model_name
1587
+ @object.present? ? @object.class.name : @object_name.to_s.classify
1588
+ end
1589
+
1590
+ def send_or_call(duck, object)
1591
+ if duck.is_a?(Proc)
1592
+ duck.call(object)
1593
+ else
1594
+ object.send(duck)
1595
+ end
1596
+ end
1597
+
1598
+ def set_include_blank(options)
1599
+ unless options.key?(:include_blank) || options.key?(:prompt)
1600
+ options[:include_blank] = @@include_blank_for_select_by_default
1601
+ end
1602
+ options
1603
+ end
1604
+
1605
+ end
1606
+
1607
+ # Wrappers around form_for (etc) with :builder => SemanticFormBuilder.
1608
+ #
1609
+ # * semantic_form_for(@post)
1610
+ # * semantic_fields_for(@post)
1611
+ # * semantic_form_remote_for(@post)
1612
+ # * semantic_remote_form_for(@post)
1613
+ #
1614
+ # Each of which are the equivalent of:
1615
+ #
1616
+ # * form_for(@post, :builder => Formtastic::SemanticFormBuilder))
1617
+ # * fields_for(@post, :builder => Formtastic::SemanticFormBuilder))
1618
+ # * form_remote_for(@post, :builder => Formtastic::SemanticFormBuilder))
1619
+ # * remote_form_for(@post, :builder => Formtastic::SemanticFormBuilder))
1620
+ #
1621
+ # Example Usage:
1622
+ #
1623
+ # <% semantic_form_for @post do |f| %>
1624
+ # <%= f.input :title %>
1625
+ # <%= f.input :body %>
1626
+ # <% end %>
1627
+ #
1628
+ # The above examples use a resource-oriented style of form_for() helper where only the @post
1629
+ # object is given as an argument, but the generic style is also supported, as are forms with
1630
+ # inline objects (Post.new) rather than objects with instance variables (@post):
1631
+ #
1632
+ # <% semantic_form_for :post, @post, :url => posts_path do |f| %>
1633
+ # ...
1634
+ # <% end %>
1635
+ #
1636
+ # <% semantic_form_for :post, Post.new, :url => posts_path do |f| %>
1637
+ # ...
1638
+ # <% end %>
1639
+ module SemanticFormHelper
1640
+ @@builder = ::Formtastic::SemanticFormBuilder
1641
+ mattr_accessor :builder
1642
+
1643
+ @@default_field_error_proc = nil
1644
+
1645
+ # Override the default ActiveRecordHelper behaviour of wrapping the input.
1646
+ # This gets taken care of semantically by adding an error class to the LI tag
1647
+ # containing the input.
1648
+ #
1649
+ FIELD_ERROR_PROC = proc do |html_tag, instance_tag|
1650
+ html_tag
1651
+ end
1652
+
1653
+ def with_custom_field_error_proc(&block)
1654
+ @@default_field_error_proc = ::ActionView::Base.field_error_proc
1655
+ ::ActionView::Base.field_error_proc = FIELD_ERROR_PROC
1656
+ result = yield
1657
+ ::ActionView::Base.field_error_proc = @@default_field_error_proc
1658
+ result
1659
+ end
1660
+
1661
+ [:form_for, :fields_for, :remote_form_for].each do |meth|
1662
+ src = <<-END_SRC
1663
+ def semantic_#{meth}(record_or_name_or_array, *args, &proc)
1664
+ options = args.extract_options!
1665
+ options[:builder] ||= @@builder
1666
+ options[:html] ||= {}
1667
+
1668
+ class_names = options[:html][:class] ? options[:html][:class].split(" ") : []
1669
+ class_names << "formtastic"
1670
+ class_names << case record_or_name_or_array
1671
+ when String, Symbol then record_or_name_or_array.to_s # :post => "post"
1672
+ when Array then ActionController::RecordIdentifier.singular_class_name(record_or_name_or_array.last.class) # [@post, @comment] # => "comment"
1673
+ else ActionController::RecordIdentifier.singular_class_name(record_or_name_or_array.class) # @post => "post"
1674
+ end
1675
+ options[:html][:class] = class_names.join(" ")
1676
+
1677
+ with_custom_field_error_proc do
1678
+ #{meth}(record_or_name_or_array, *(args << options), &proc)
1679
+ end
1680
+ end
1681
+ END_SRC
1682
+ module_eval src, __FILE__, __LINE__
1683
+ end
1684
+ alias :semantic_form_remote_for :semantic_remote_form_for
1685
+
1686
+ end
1687
+ end