ShadowBelmolve-formtastic 0.1.6

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.
data/lib/formtastic.rb ADDED
@@ -0,0 +1,1325 @@
1
+ # Override the default ActiveRecordHelper behaviour of wrapping the input.
2
+ # This gets taken care of semantically by adding an error class to the LI tag
3
+ # containing the input.
4
+ ActionView::Base.field_error_proc = proc do |html_tag, instance_tag|
5
+ html_tag
6
+ end
7
+
8
+ module Formtastic #:nodoc:
9
+
10
+ class SemanticFormBuilder < ActionView::Helpers::FormBuilder
11
+
12
+ @@default_text_field_size = 50
13
+ @@all_fields_required_by_default = true
14
+ @@required_string = proc { %{<abbr title="#{I18n.t 'formtastic.required', :default => 'required'}">*</abbr>} }
15
+ @@optional_string = ''
16
+ @@inline_errors = :sentence
17
+ @@label_str_method = :humanize
18
+ @@collection_label_methods = %w[to_label display_name full_name name title username login value to_s]
19
+ @@inline_order = [ :input, :hints, :errors ]
20
+ @@file_methods = [ :file?, :public_filename ]
21
+
22
+ cattr_accessor :default_text_field_size, :all_fields_required_by_default, :required_string,
23
+ :optional_string, :inline_errors, :label_str_method, :collection_label_methods,
24
+ :inline_order, :file_methods
25
+
26
+ # Keeps simple mappings in a hash
27
+ #
28
+ INPUT_MAPPINGS = {
29
+ :string => :text_field,
30
+ :password => :password_field,
31
+ :numeric => :text_field,
32
+ :text => :text_area,
33
+ :file => :file_field
34
+ }
35
+ STRING_MAPPINGS = [ :string, :password, :numeric ]
36
+
37
+ attr_accessor :template
38
+
39
+ # Returns a suitable form input for the given +method+, using the database column information
40
+ # and other factors (like the method name) to figure out what you probably want.
41
+ #
42
+ # Options:
43
+ #
44
+ # * :as - override the input type (eg force a :string to render as a :password field)
45
+ # * :label - use something other than the method name as the label (or fieldset legend) text
46
+ # * :required - specify if the column is required (true) or not (false)
47
+ # * :hint - provide some text to hint or help the user provide the correct information for a field
48
+ # * :input_html - provide options that will be passed down to the generated input
49
+ #
50
+ # Input Types:
51
+ #
52
+ # Most inputs map directly to one of ActiveRecord's column types by default (eg string_input),
53
+ # but there are a few special cases and some simplification (:integer, :float and :decimal
54
+ # columns all map to a single numeric_input, for example).
55
+ #
56
+ # * :select (a select menu for associations) - default to association names
57
+ # * :time_zone (a select menu with time zones)
58
+ # * :radio (a set of radio inputs for associations) - default to association names
59
+ # * :password (a password input) - default for :string column types with 'password' in the method name
60
+ # * :text (a textarea) - default for :text column types
61
+ # * :date (a date select) - default for :date column types
62
+ # * :datetime (a date and time select) - default for :datetime and :timestamp column types
63
+ # * :time (a time select) - default for :time column types
64
+ # * :boolean (a checkbox) - default for :boolean column types (you can also have booleans as :select and :radio)
65
+ # * :string (a text field) - default for :string column types
66
+ # * :numeric (a text field, like string) - default for :integer, :float and :decimal column types
67
+ #
68
+ # Example:
69
+ #
70
+ # <% semantic_form_for @employee do |form| %>
71
+ # <% form.inputs do -%>
72
+ # <%= form.input :name, :label => "Full Name"%>
73
+ # <%= form.input :manager_id, :as => :radio %>
74
+ # <%= form.input :hired_at, :as => :date, :label => "Date Hired" %>
75
+ # <%= form.input :phone, :required => false, :hint => "Eg: +1 555 1234" %>
76
+ # <% end %>
77
+ # <% end %>
78
+ #
79
+ def input(method, options = {})
80
+ options[:required] = method_required?(method, options[:required])
81
+ options[:as] ||= default_input_type(method)
82
+
83
+ options[:label] ||= if @object && @object.class.respond_to?(:human_attribute_name)
84
+ @object.class.human_attribute_name(method.to_s)
85
+ else
86
+ method.to_s.send(@@label_str_method)
87
+ end
88
+
89
+ if [:boolean_select, :boolean_radio].include?(options[:as])
90
+ ::ActiveSupport::Deprecation.warn(":as => :#{options[:as]} is deprecated, use :as => :#{options[:as].to_s[8..-1]} instead", caller[3..-1])
91
+ end
92
+
93
+ html_class = [ options[:as], (options[:required] ? :required : :optional) ].join(' ')
94
+ html_class << ' error' if @object && @object.respond_to?(:errors) && @object.errors.on(method.to_s)
95
+
96
+ html_id = generate_html_id(method)
97
+
98
+ list_item_content = @@inline_order.map do |type|
99
+ send(:"inline_#{type}_for", method, options)
100
+ end.compact.join("\n")
101
+
102
+ return template.content_tag(:li, list_item_content, { :id => html_id, :class => html_class })
103
+ end
104
+
105
+ # Creates an input fieldset and ol tag wrapping for use around a set of inputs. It can be
106
+ # called either with a block (in which you can do the usual Rails form stuff, HTML, ERB, etc),
107
+ # or with a list of fields. These two examples are functionally equivalent:
108
+ #
109
+ # # With a block:
110
+ # <% semantic_form_for @post do |form| %>
111
+ # <% form.inputs do %>
112
+ # <%= form.input :title %>
113
+ # <%= form.input :body %>
114
+ # <% end %>
115
+ # <% end %>
116
+ #
117
+ # # With a list of fields:
118
+ # <% semantic_form_for @post do |form| %>
119
+ # <%= form.inputs :title, :body %>
120
+ # <% end %>
121
+ #
122
+ # # Output:
123
+ # <form ...>
124
+ # <fieldset class="inputs">
125
+ # <ol>
126
+ # <li class="string">...</li>
127
+ # <li class="text">...</li>
128
+ # </ol>
129
+ # </fieldset>
130
+ # </form>
131
+ #
132
+ # === Quick Forms
133
+ #
134
+ # When called without a block or a field list, an input is rendered for each column in the
135
+ # model's database table, just like Rails' scaffolding. You'll obviously want more control
136
+ # than this in a production application, but it's a great way to get started, then come back
137
+ # later to customise the form with a field list or a block of inputs. Example:
138
+ #
139
+ # <% semantic_form_for @post do |form| %>
140
+ # <%= form.inputs %>
141
+ # <% end %>
142
+ #
143
+ # === Options
144
+ #
145
+ # All options (with the exception of :name) are passed down to the fieldset as HTML
146
+ # attributes (id, class, style, etc). If provided, the :name option is passed into a
147
+ # legend tag inside the fieldset (otherwise a legend is not generated).
148
+ #
149
+ # # With a block:
150
+ # <% semantic_form_for @post do |form| %>
151
+ # <% form.inputs :name => "Create a new post", :style => "border:1px;" do %>
152
+ # ...
153
+ # <% end %>
154
+ # <% end %>
155
+ #
156
+ # # With a list (the options must come after the field list):
157
+ # <% semantic_form_for @post do |form| %>
158
+ # <%= form.inputs :title, :body, :name => "Create a new post", :style => "border:1px;" %>
159
+ # <% end %>
160
+ #
161
+ # === It's basically a fieldset!
162
+ #
163
+ # Instead of hard-coding fieldsets & legends into your form to logically group related fields,
164
+ # use inputs:
165
+ #
166
+ # <% semantic_form_for @post do |f| %>
167
+ # <% f.inputs do %>
168
+ # <%= f.input :title %>
169
+ # <%= f.input :body %>
170
+ # <% end %>
171
+ # <% f.inputs :name => "Advanced", :id => "advanced" do %>
172
+ # <%= f.input :created_at %>
173
+ # <%= f.input :user_id, :label => "Author" %>
174
+ # <% end %>
175
+ # <% end %>
176
+ #
177
+ # # Output:
178
+ # <form ...>
179
+ # <fieldset class="inputs">
180
+ # <ol>
181
+ # <li class="string">...</li>
182
+ # <li class="text">...</li>
183
+ # </ol>
184
+ # </fieldset>
185
+ # <fieldset class="inputs" id="advanced">
186
+ # <legend><span>Advanced</span></legend>
187
+ # <ol>
188
+ # <li class="datetime">...</li>
189
+ # <li class="select">...</li>
190
+ # </ol>
191
+ # </fieldset>
192
+ # </form>
193
+ #
194
+ # === Nested attributes
195
+ #
196
+ # As in Rails, you can use semantic_fields_for to nest attributes:
197
+ #
198
+ # <% semantic_form_for @post do |form| %>
199
+ # <%= form.inputs :title, :body %>
200
+ #
201
+ # <% form.semantic_fields_for :author, @bob do |author_form| %>
202
+ # <% author_form.inputs do %>
203
+ # <%= author_form.input :first_name, :required => false %>
204
+ # <%= author_form.input :last_name %>
205
+ # <% end %>
206
+ # <% end %>
207
+ # <% end %>
208
+ #
209
+ # But this does not look formtastic! This is equivalent:
210
+ #
211
+ # <% semantic_form_for @post do |form| %>
212
+ # <%= form.inputs :title, :body %>
213
+ # <% form.inputs :for => [ :author, @bob ] do |author_form| %>
214
+ # <%= author_form.input :first_name, :required => false %>
215
+ # <%= author_form.input :last_name %>
216
+ # <% end %>
217
+ # <% end %>
218
+ #
219
+ # And if you don't need to give options to your input call, you could do it
220
+ # in just one line:
221
+ #
222
+ # <% semantic_form_for @post do |form| %>
223
+ # <%= form.inputs :title, :body %>
224
+ # <%= form.inputs :first_name, :last_name, :for => @bob %>
225
+ # <% end %>
226
+ #
227
+ # Just remember that calling inputs generates a new fieldset to wrap your
228
+ # inputs. If you have two separate models, but, semantically, on the page
229
+ # they are part of the same fieldset, you should use semantic_fields_for
230
+ # instead (just as you would do with Rails' form builder).
231
+ #
232
+ def inputs(*args, &block)
233
+ html_options = args.extract_options!
234
+ html_options[:class] ||= "inputs"
235
+
236
+ if html_options[:for]
237
+ inputs_for_nested_attributes(args, html_options, &block)
238
+ elsif block_given?
239
+ field_set_and_list_wrapping(html_options, &block)
240
+ else
241
+ if @object && args.empty?
242
+ args = @object.class.reflections.map { |n,_| n if _.macro == :belongs_to }
243
+ args += @object.class.content_columns.map(&:name)
244
+ args -= %w[created_at updated_at created_on updated_on]
245
+ args.compact!
246
+ end
247
+ contents = args.map { |method| input(method.to_sym) }
248
+
249
+ field_set_and_list_wrapping(html_options, contents)
250
+ end
251
+ end
252
+ alias :input_field_set :inputs
253
+
254
+ # Creates a fieldset and ol tag wrapping for form buttons / actions as list items.
255
+ # See inputs documentation for a full example. The fieldset's default class attriute
256
+ # is set to "buttons".
257
+ #
258
+ # See inputs for html attributes and special options.
259
+ def buttons(*args, &block)
260
+ html_options = args.extract_options!
261
+ html_options[:class] ||= "buttons"
262
+
263
+ if block_given?
264
+ field_set_and_list_wrapping(html_options, &block)
265
+ else
266
+ args = [:commit] if args.empty?
267
+ contents = args.map { |button_name| send(:"#{button_name}_button") }
268
+ field_set_and_list_wrapping(html_options, contents)
269
+ end
270
+ end
271
+ alias :button_field_set :buttons
272
+
273
+ # Creates a submit input tag with the value "Save [model name]" (for existing records) or
274
+ # "Create [model name]" (for new records) by default:
275
+ #
276
+ # <%= form.commit_button %> => <input name="commit" type="submit" value="Save Post" />
277
+ #
278
+ # The value of the button text can be overridden:
279
+ #
280
+ # <%= form.commit_button "Go" %> => <input name="commit" type="submit" value="Go" />
281
+ #
282
+ def commit_button(value=nil, options={})
283
+ value ||= save_or_create_button_text
284
+ button_html = options.delete(:button_html) || {}
285
+ template.content_tag(:li, self.submit(value, button_html), :class => "commit")
286
+ end
287
+
288
+ # A thin wrapper around #fields_for to set :builder => Formtastic::SemanticFormBuilder
289
+ # for nesting forms:
290
+ #
291
+ # # Example:
292
+ # <% semantic_form_for @post do |post| %>
293
+ # <% post.semantic_fields_for :author do |author| %>
294
+ # <% author.inputs :name %>
295
+ # <% end %>
296
+ # <% end %>
297
+ #
298
+ # # Output:
299
+ # <form ...>
300
+ # <fieldset class="inputs">
301
+ # <ol>
302
+ # <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
303
+ # </ol>
304
+ # </fieldset>
305
+ # </form>
306
+ #
307
+ def semantic_fields_for(record_or_name_or_array, *args, &block)
308
+ opts = args.extract_options!
309
+ opts.merge!(:builder => Formtastic::SemanticFormBuilder)
310
+ args.push(opts)
311
+ fields_for(record_or_name_or_array, *args, &block)
312
+ end
313
+
314
+ #
315
+ # Stolen from Attribute_fu (http://github.com/giraffesoft/attribute_fu)
316
+ # Rails 2.3 Patches from http://github.com/odadata/attribute_fu
317
+ #
318
+ # Dinamically add and remove nested forms for a has_many relation.
319
+ #
320
+
321
+ # Add a link to remove the associated partial
322
+ # # Example:
323
+ # <% semantic_form_for @post do |post| %>
324
+ # <%= post.input :title %>
325
+ # <% post.inputs :name => 'Authors', :id => 'authors' do %>
326
+ # <%= post.add_associated_link "+ Author", :authors, :partial => 'authors/add_author' %>
327
+ # <%= post.render_associated_form :authors, :partial => 'authors/add_author' %>
328
+ # <% end %>
329
+ # <% end %>
330
+ #
331
+ # # app/views/authors/_add_author.html.erb
332
+ # <div class="author">
333
+ # <%= f.input :name %>
334
+ # <%= f.remove_link "Remove" %>
335
+ # </div>
336
+ #
337
+ # # Output:
338
+ # <form ...>
339
+ # <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
340
+ # <fieldset class="inputs" id="authors"><legend><span>Authors</span></legend><ol>
341
+ # <a href="#" onclick="if (typeof formtastic_next_author_id == 'undefined') ....return false;">+ Author</a>
342
+ # <div class="author">
343
+ # <li ...><label ...></label><input id="post_authors_name" maxlength="255"
344
+ # name="post[authors][name]" size="50" type="text" /></li>
345
+ # <input id="post_authors__delete" name="post[authors][_delete]" type="hidden" />
346
+ # <a href="#" onclick="$(this).parents('.author').hide(); $(this).prev(':input').val('1');; return false;">Remove</a>
347
+ # </div>
348
+ # </ol></fieldset>
349
+ # </form>
350
+ #
351
+ # * Opts
352
+ # * :selector, id of element that will disappear(.hide()), if no id as give, will use css class
353
+ # association.class.name last word in downcase #=> '.author'
354
+ # f.remove_link "Remove", :selector => '#my_own_element_id'
355
+ #
356
+ # * :function, a funcion to execute before hide element and set _delete to 1
357
+ # f.remove_link "Remove", :function => "alert('Removing Author')"
358
+ #
359
+ #
360
+ # NOTE: remove_link must be put in the partial, not in main template
361
+ #
362
+
363
+ def remove_link(name, *args)
364
+ options = args.extract_options!
365
+ css_selector = options.delete(:selector) || ".#{@object.class.name.split("::").last.underscore}"
366
+
367
+ function = options.delete(:function) || ""
368
+ function << ";$(this).parents('#{css_selector}').hide(); $(this).prev(':input').val('1');"
369
+
370
+ out = hidden_field(:_delete)
371
+ out += template.link_to_function(name, function, *args.push(options))
372
+ end
373
+
374
+ # Add a link to add more partials
375
+ # # Example:
376
+ # <% semantic_form_for @post do |post| %>
377
+ # <%= post.input :title %>
378
+ # <% post.inputs :name => 'Authors', :id => 'authors' do %>
379
+ # <%= post.add_associated_link "+ Author", :authors, :partial => 'authors/add_author' %>
380
+ # <% end %>
381
+ # <% end %>
382
+ #
383
+ # # app/views/authors/_add_author.html.erb
384
+ # <% f.input :name %>
385
+ #
386
+ # # Output:
387
+ # <form ...>
388
+ # <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
389
+ # <fieldset class="inputs" id="authors"><legend><span>Authors</span></legend><ol>
390
+ # <a href="#" onclick="if (typeof formtastic_next_author_id == 'undefined') ....return false;">+ Author</a>
391
+ # </ol></fieldset>
392
+ # </form>
393
+ #
394
+ # if no partial name as give, it will use the association name 'authors' #=> app/views/posts/_authors.html.erb
395
+ # you can use :container to customize the container of nesteds #=> :container => '#my_authors'
396
+ # :before_function will be executed before the add method
397
+ # :after_function will be executed after
398
+ #
399
+ #
400
+ def add_associated_link(name, association, opts = {})
401
+ object = @object.send(association).build
402
+ associated_name = extract_option_or_class_name(opts, :name, object)
403
+ variable = "formtastic_next_#{associated_name}_id"
404
+
405
+ opts.symbolize_keys!
406
+ partial = opts.delete(:partial) || associated_name
407
+ container = opts.delete(:expression) || "'#{opts.delete(:container) || '#'+associated_name.pluralize}'"
408
+ before_function = opts.delete(:before_function) || ''
409
+ after_function = opts.delete(:after_function) || ''
410
+
411
+ form = self.render_associated_form(object, :partial => partial)
412
+ form.gsub!(/attributes_(\d+)/, '__idx__')
413
+ form.gsub!(/\[(\d+)\]/, '__idxx__')
414
+
415
+ function = "#{before_function};if (typeof #{variable} == 'undefined') #{variable} = #{$1 || 0};
416
+ $(#{container}).append(#{form.to_json}.replace(/__idx__/g, 'attributes_' +
417
+ #{variable}).replace(/__idxx__/g, '[' + #{variable}++ + ']'));#{after_function}"
418
+
419
+ template.link_to_function(name, function, opts)
420
+ end
421
+
422
+ # Render associated form
423
+ # # Example:
424
+ # <% semantic_form_for @post do |post| %>
425
+ # <%= post.input :title %>
426
+ # <% post.inputs :name => 'Authors', :id => 'authors' do %>
427
+ # <%= post.add_associated_link "+ Author", :authors, :partial => 'authors/add_author' %>
428
+ # <%= post.render_associated_form :authors, :partial => 'authors/add_author' %>
429
+ # <% end %>
430
+ # <% end %>
431
+ #
432
+ # # app/views/authors/_add_author.html.erb
433
+ # <% f.input :name %>
434
+ #
435
+ # # Output:
436
+ # <form ...>
437
+ # <li class="string"><input type='text' name='post[author][name]' id='post_author_name' /></li>
438
+ # <fieldset class="inputs" id="authors"><legend><span>Authors</span></legend><ol>
439
+ # <a href="#" onclick="if (typeof formtastic_next_author_id == 'undefined') ....return false;">+ Author</a>
440
+ # <li class="string required" ...><label ...></label><input id="post_authors_name" maxlength="255"
441
+ # name="post[authors][name]" size="50" type="text" value="Renan T. Fernandes" /></li>
442
+ # </ol></fieldset>
443
+ # </form>
444
+ #
445
+ # Opts
446
+ # * :partial, render a partial, if not partial is given, try to find a partial with association
447
+ # name in the controller folder.
448
+ # post.render_associated_form :authors, :partial => 'author'
449
+ # ^ try to render app/views/posts/_author.html.erb
450
+ # post.render_associated_form :authors, :partial => 'authors/author'
451
+ # ^ try to render app/views/authors/_author.html.erb
452
+ # NOTE: Partial need to use 'f' as formtastic reference
453
+ # Example:
454
+ # <%= f.input :name %> #=> render author name association
455
+ #
456
+ # * :new make X empty partials if is a new record
457
+ # Examples:
458
+ # post.render_associated_form :authors, :new => 2
459
+ # ^ make 2 empty authors partials
460
+ #
461
+ # * :edit show only X partial if is editing a record
462
+ # post.render_associated_form :authors, :edit => 3
463
+ # ^ if record have 1 author, make 2 new empty partials
464
+ # NOTE: :edit not conflicts with :new; :new is for new records only
465
+ #
466
+ # * :new_in_edit show X new partial if is editing a record
467
+ # post.render_associated_form :authors, :new_in_edit => 2
468
+ # ^ make more 2 new partial for record
469
+ # NOTE: this option is ignored if :edit is seted
470
+ # Example:
471
+ # post.render_associated_form :authors, :edit => 2, :new_in_edit => 100
472
+ # ^ if record have 1 author, make more one partial
473
+ #
474
+ #
475
+ def render_associated_form(associated, opts = {})
476
+ associated = @object.send(associated.to_s) if associated.is_a? Symbol
477
+ associated = associated.is_a?(Array) ? associated : [associated] # preserve association proxy if this is one
478
+
479
+ opts.symbolize_keys!
480
+ (opts[:new] - associated.select(&:new_record?).length).times { associated.build } if opts[:new] and @object.new_record? == true
481
+ if opts[:edit] and @object.new_record? == false
482
+ (opts[:edit] - associated.count).times { associated.build }
483
+ elsif opts[:new_in_edit] and @object.new_record? == false
484
+ opts[:new_in_edit].times { associated.build }
485
+ end
486
+
487
+
488
+ unless associated.empty?
489
+ name = extract_option_or_class_name(opts, :name, associated.first)
490
+ partial = opts[:partial] || name
491
+ local_assign_name = partial.split('/').last.split('.').first
492
+
493
+ output = associated.map do |element|
494
+ fields_for(association_name(name), element, (opts[:fields_for] || {}).merge(:name => name)) do |f|
495
+ template.render({:partial => "#{partial}", :locals => {local_assign_name.to_sym => element, :f => f}.merge(opts[:locals] || {})}.merge(opts[:render] || {}))
496
+ end
497
+ end
498
+ output.join
499
+ end
500
+ end
501
+
502
+ private
503
+
504
+ def association_name(class_name)
505
+ @object.respond_to?("#{class_name}_attributes=") ? class_name : class_name.pluralize
506
+ end
507
+
508
+ def extract_option_or_class_name(hash, option, object)
509
+ (hash.delete(option) || object.class.name.split('::').last.underscore)
510
+ end
511
+ # End attribute_fu magic #
512
+
513
+ protected
514
+
515
+ # Deals with :for option when it's supplied to inputs methods. Additional
516
+ # options to be passed down to :for should be supplied using :for_options
517
+ # key.
518
+ #
519
+ # It should raise an error if a block with arity zero is given.
520
+ #
521
+ def inputs_for_nested_attributes(args, options, &block)
522
+ args << options.merge!(:parent => { :builder => self, :for => options[:for] })
523
+
524
+ fields_for_block = if block_given?
525
+ raise ArgumentError, 'You gave :for option with a block to inputs method, ' <<
526
+ 'but the block does not accept any argument.' if block.arity <= 0
527
+
528
+ proc { |f| f.inputs(*args){ block.call(f) } }
529
+ else
530
+ proc { |f| f.inputs(*args) }
531
+ end
532
+
533
+ fields_for_args = [options.delete(:for), options.delete(:for_options) || {}].flatten
534
+ semantic_fields_for(*fields_for_args, &fields_for_block)
535
+ end
536
+
537
+ # Remove any Formtastic-specific options before passing the down options.
538
+ #
539
+ def set_options(options)
540
+ options.except(:value_method, :label_method, :collection, :required, :label,
541
+ :as, :hint, :input_html, :label_html, :value_as_class)
542
+ end
543
+
544
+ # Create a default button text. If the form is working with a object, it
545
+ # defaults to "Create model" or "Save model" depending if we are working
546
+ # with a new_record or not.
547
+ #
548
+ # When not working with models, it defaults to "Submit object".
549
+ #
550
+ def save_or_create_button_text(prefix='Submit') #:nodoc:
551
+ if @object
552
+ prefix = @object.new_record? ? 'Create' : 'Save'
553
+ object_name = @object.class.human_name
554
+ else
555
+ object_name = @object_name.to_s.send(@@label_str_method)
556
+ end
557
+
558
+ I18n.t(prefix.downcase, :default => prefix, :scope => [:formtastic]) << ' ' << object_name
559
+ end
560
+
561
+ # Determins if the attribute (eg :title) should be considered required or not.
562
+ #
563
+ # * if the :required option was provided in the options hash, the true/false value will be
564
+ # returned immediately, allowing the view to override any guesswork that follows:
565
+ #
566
+ # * if the :required option isn't provided in the options hash, and the ValidationReflection
567
+ # plugin is installed (http://github.com/redinger/validation_reflection), true is returned
568
+ # if the validates_presence_of macro has been used in the class for this attribute, or false
569
+ # otherwise.
570
+ #
571
+ # * if the :required option isn't provided, and the plugin isn't available, the value of the
572
+ # configuration option @@all_fields_required_by_default is used.
573
+ #
574
+ def method_required?(attribute, required_option) #:nodoc:
575
+ return required_option unless required_option.nil?
576
+
577
+ if @object && @object.class.respond_to?(:reflect_on_all_validations)
578
+ attribute_sym = attribute.to_s.sub(/_id$/, '').to_sym
579
+
580
+ @object.class.reflect_on_all_validations.any? do |validation|
581
+ validation.macro == :validates_presence_of && validation.name == attribute_sym
582
+ end
583
+ else
584
+ @@all_fields_required_by_default
585
+ end
586
+ end
587
+
588
+ # A method that deals with most of inputs (:string, :password, :file,
589
+ # :textarea and :numeric). :select, :radio, :boolean and :datetime inputs
590
+ # are not handled by this method, since they need more detailed approach.
591
+ #
592
+ # If input_html is given as option, it's passed down to the input.
593
+ #
594
+ def input_simple(type, method, options)
595
+ html_options = options.delete(:input_html) || {}
596
+ html_options = default_string_options(method).merge(html_options) if STRING_MAPPINGS.include?(type)
597
+
598
+ input_label(method, options.delete(:label), options.slice(:required)) + send(INPUT_MAPPINGS[type], method, html_options)
599
+ end
600
+
601
+ # Outputs a label and a select box containing options from the parent
602
+ # (belongs_to, has_many, has_and_belongs_to_many) association. If an association
603
+ # is has_many or has_and_belongs_to_many the select box will be set as multi-select
604
+ # and size = 5
605
+ #
606
+ # Example (belongs_to):
607
+ #
608
+ # f.input :author
609
+ #
610
+ # <label for="book_author_id">Author</label>
611
+ # <select id="book_author_id" name="book[author_id]">
612
+ # <option value="1">Justin French</option>
613
+ # <option value="2">Jane Doe</option>
614
+ # </select>
615
+ #
616
+ # Example (has_many):
617
+ #
618
+ # f.input :chapters
619
+ #
620
+ # <label for="book_chapter_ids">Chapters</label>
621
+ # <select id="book_chapter_ids" name="book[chapter_ids]">
622
+ # <option value="1">Chapter 1</option>
623
+ # <option value="2">Chapter 2</option>
624
+ # </select>
625
+ #
626
+ # Example (has_and_belongs_to_many):
627
+ #
628
+ # f.input :authors
629
+ #
630
+ # <label for="book_author_ids">Authors</label>
631
+ # <select id="book_author_ids" name="book[author_ids]">
632
+ # <option value="1">Justin French</option>
633
+ # <option value="2">Jane Doe</option>
634
+ # </select>
635
+ #
636
+ #
637
+ # You can customize the options available in the select by passing in a collection (Array) of
638
+ # ActiveRecord objects through the :collection option. If not provided, the choices are found
639
+ # by inferring the parent's class name from the method name and simply calling find(:all) on
640
+ # it (VehicleOwner.find(:all) in the example above).
641
+ #
642
+ # Examples:
643
+ #
644
+ # f.input :author, :collection => @authors
645
+ # f.input :author, :collection => Author.find(:all)
646
+ # f.input :author, :collection => [@justin, @kate]
647
+ # f.input :author, :collection => {@justin.name => @justin.id, @kate.name => @kate.id}
648
+ #
649
+ # Note: This input looks for a label method in the parent association.
650
+ #
651
+ # You can customize the text label inside each option tag, by naming the correct method
652
+ # (:full_name, :display_name, :account_number, etc) to call on each object in the collection
653
+ # by passing in the :label_method option. By default the :label_method is whichever element of
654
+ # Formtastic::SemanticFormBuilder.collection_label_methods is found first.
655
+ #
656
+ # Examples:
657
+ #
658
+ # f.input :author, :label_method => :full_name
659
+ # f.input :author, :label_method => :display_name
660
+ # f.input :author, :label_method => :to_s
661
+ # f.input :author, :label_method => :label
662
+ #
663
+ # You can also customize the value inside each option tag, by passing in the :value_method option.
664
+ # Usage is the same as the :label_method option
665
+ #
666
+ # Examples:
667
+ #
668
+ # f.input :author, :value_method => :full_name
669
+ # f.input :author, :value_method => :display_name
670
+ # f.input :author, :value_method => :to_s
671
+ # f.input :author, :value_method => :value
672
+ #
673
+ # You can pass html_options to the select tag using :input_html => {}
674
+ #
675
+ # Examples:
676
+ #
677
+ # f.input :authors, :input_html => {:size => 20, :multiple => true}
678
+ #
679
+ def select_input(method, options)
680
+ collection = find_collection_for_column(method, options)
681
+ html_options = options.delete(:input_html) || {}
682
+
683
+ reflection = find_reflection(method)
684
+ if reflection && [ :has_many, :has_and_belongs_to_many ].include?(reflection.macro)
685
+ html_options[:multiple] ||= true
686
+ html_options[:size] ||= 5
687
+ end
688
+
689
+ input_name = generate_association_input_name(method)
690
+ input_label(input_name, options.delete(:label), options.slice(:required)) +
691
+ self.select(input_name, collection, set_options(options), html_options)
692
+ end
693
+ alias :boolean_select_input :select_input
694
+
695
+ # Output ...
696
+ def time_zone_input(method, options)
697
+ html_options = options.delete(:input_html) || {}
698
+
699
+ input_name = generate_association_input_name(method)
700
+ input_label(input_name, options.delete(:label), options.slice(:required)) +
701
+ self.time_zone_select(input_name, options.delete(:priority_zones), set_options(options), html_options)
702
+ end
703
+
704
+ # Outputs a fieldset containing a legend for the label text, and an ordered list (ol) of list
705
+ # items, one for each possible choice in the belongs_to association. Each li contains a
706
+ # label and a radio input.
707
+ #
708
+ # Example:
709
+ #
710
+ # f.input :author, :as => :radio
711
+ #
712
+ # Output:
713
+ #
714
+ # <fieldset>
715
+ # <legend><span>Author</span></legend>
716
+ # <ol>
717
+ # <li>
718
+ # <label for="book_author_id_1"><input id="book_author_id_1" name="book[author_id]" type="radio" value="1" /> Justin French</label>
719
+ # </li>
720
+ # <li>
721
+ # <label for="book_author_id_2"><input id="book_author_id_2" name="book[owner_id]" type="radio" value="2" /> Kate French</label>
722
+ # </li>
723
+ # </ol>
724
+ # </fieldset>
725
+ #
726
+ # You can customize the options available in the set by passing in a collection (Array) of
727
+ # ActiveRecord objects through the :collection option. If not provided, the choices are found
728
+ # by inferring the parent's class name from the method name and simply calling find(:all) on
729
+ # it (VehicleOwner.find(:all) in the example above).
730
+ #
731
+ # Examples:
732
+ #
733
+ # f.input :author, :as => :radio, :collection => @authors
734
+ # f.input :author, :as => :radio, :collection => Author.find(:all)
735
+ # f.input :author, :as => :radio, :collection => [@justin, @kate]
736
+ #
737
+ # You can also customize the text label inside each option tag, by naming the correct method
738
+ # (:full_name, :display_name, :account_number, etc) to call on each object in the collection
739
+ # by passing in the :label_method option. By default the :label_method is whichever element of
740
+ # Formtastic::SemanticFormBuilder.collection_label_methods is found first.
741
+ #
742
+ # Examples:
743
+ #
744
+ # f.input :author, :as => :radio, :label_method => :full_name
745
+ # f.input :author, :as => :radio, :label_method => :display_name
746
+ # f.input :author, :as => :radio, :label_method => :to_s
747
+ # f.input :author, :as => :radio, :label_method => :label
748
+ #
749
+ # Finally, you can set :value_as_class => true if you want that LI wrappers
750
+ # contains a class with the wrapped radio input value.
751
+ #
752
+ def radio_input(method, options)
753
+ collection = find_collection_for_column(method, options)
754
+ html_options = set_options(options).merge(options.delete(:input_html) || {})
755
+
756
+ input_name = generate_association_input_name(method)
757
+ value_as_class = options.delete(:value_as_class)
758
+
759
+ list_item_content = collection.map do |c|
760
+ label = c.is_a?(Array) ? c.first : c
761
+ value = c.is_a?(Array) ? c.last : c
762
+
763
+ li_content = template.content_tag(:label,
764
+ "#{self.radio_button(input_name, value, html_options)} #{label}",
765
+ :for => generate_html_id(input_name, value.to_s.downcase)
766
+ )
767
+
768
+ li_options = value_as_class ? { :class => value.to_s.downcase } : {}
769
+ template.content_tag(:li, li_content, li_options)
770
+ end
771
+
772
+ field_set_and_list_wrapping_for_method(method, options, list_item_content)
773
+ end
774
+ alias :boolean_radio_input :radio_input
775
+
776
+
777
+
778
+
779
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
780
+ # items (li), one for each fragment for the date (year, month, day). Each li contains a label
781
+ # (eg "Year") and a select box. See date_or_datetime_input for a more detailed output example.
782
+ #
783
+ # Some of Rails' options for select_date are supported, but not everything yet.
784
+ def date_input(method, options)
785
+ date_or_datetime_input(method, options.merge(:discard_hour => true))
786
+ end
787
+
788
+
789
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
790
+ # items (li), one for each fragment for the date (year, month, day, hour, min, sec). Each li
791
+ # contains a label (eg "Year") and a select box. See date_or_datetime_input for a more
792
+ # detailed output example.
793
+ #
794
+ # Some of Rails' options for select_date are supported, but not everything yet.
795
+ def datetime_input(method, options)
796
+ date_or_datetime_input(method, options)
797
+ end
798
+
799
+
800
+ # Outputs a fieldset with a legend for the method label, and a ordered list (ol) of list
801
+ # items (li), one for each fragment for the time (hour, minute, second). Each li contains a label
802
+ # (eg "Hour") and a select box. See date_or_datetime_input for a more detailed output example.
803
+ #
804
+ # Some of Rails' options for select_time are supported, but not everything yet.
805
+ def time_input(method, options)
806
+ date_or_datetime_input(method, options.merge(:discard_year => true, :discard_month => true, :discard_day => true))
807
+ end
808
+
809
+
810
+ # <fieldset>
811
+ # <legend>Created At</legend>
812
+ # <ol>
813
+ # <li>
814
+ # <label for="user_created_at_1i">Year</label>
815
+ # <select id="user_created_at_1i" name="user[created_at(1i)]">
816
+ # <option value="2003">2003</option>
817
+ # ...
818
+ # <option value="2013">2013</option>
819
+ # </select>
820
+ # </li>
821
+ # <li>
822
+ # <label for="user_created_at_2i">Month</label>
823
+ # <select id="user_created_at_2i" name="user[created_at(2i)]">
824
+ # <option value="1">January</option>
825
+ # ...
826
+ # <option value="12">December</option>
827
+ # </select>
828
+ # </li>
829
+ # <li>
830
+ # <label for="user_created_at_3i">Day</label>
831
+ # <select id="user_created_at_3i" name="user[created_at(3i)]">
832
+ # <option value="1">1</option>
833
+ # ...
834
+ # <option value="31">31</option>
835
+ # </select>
836
+ # </li>
837
+ # </ol>
838
+ # </fieldset>
839
+ #
840
+ # This is an absolute abomination, but so is the official Rails select_date().
841
+ #
842
+ def date_or_datetime_input(method, options)
843
+ position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
844
+ inputs = options.delete(:order) || I18n.translate(:'date.order') || [:year, :month, :day]
845
+
846
+ time_inputs = [:hour, :minute]
847
+ time_inputs << [:second] if options[:include_seconds]
848
+
849
+ list_items_capture = ""
850
+
851
+ # Gets the datetime object. It can be a Fixnum, Date or Time, or nil.
852
+ datetime = @object ? @object.send(method) : nil
853
+ html_options = options.delete(:input_html) || {}
854
+
855
+ (inputs + time_inputs).each do |input|
856
+ html_id = generate_html_id(method, "#{position[input]}i")
857
+ field_name = "#{method}(#{position[input]}i)"
858
+
859
+ list_items_capture << if options["discard_#{input}".intern]
860
+ break if time_inputs.include?(input)
861
+
862
+ hidden_value = datetime.respond_to?(input) ? datetime.send(input) : datetime
863
+ template.hidden_field_tag("#{@object_name}[#{field_name}]", (hidden_value || 1), :id => html_id)
864
+ else
865
+ opts = set_options(options).merge(:prefix => @object_name, :field_name => field_name)
866
+ item_label_text = I18n.t(input.to_s, :default => input.to_s.humanize, :scope => [:datetime, :prompts])
867
+
868
+ template.content_tag(:li,
869
+ template.content_tag(:label, item_label_text, :for => html_id) +
870
+ template.send("select_#{input}".intern, datetime, opts, html_options.merge(:id => html_id))
871
+ )
872
+ end
873
+ end
874
+
875
+ field_set_and_list_wrapping_for_method(method, options, list_items_capture)
876
+ end
877
+
878
+ # Add a list of checkboxes, like radio
879
+ #
880
+ # Example:
881
+ # Link
882
+ # belongs_to :author
883
+ # belongs_to :post
884
+ #
885
+ # Author
886
+ # has_many :links
887
+ # has_many :posts, :through => :links
888
+ #
889
+ # Post
890
+ # has_many :links
891
+ # has_many :authors, :through => :links
892
+ #
893
+ # # posts/new.html.erb
894
+ # <% semantic_form_for @post do |post| %>
895
+ # <%= post.input :title %>
896
+ # <h3>This post belongs to<h3>
897
+ # <%= post.input :author, :as => :check_boxes %>
898
+ # <% end %>
899
+ #
900
+ # # Output
901
+ # ...
902
+ # <li class="check_boxes required" id="post_authors_input">
903
+ # <fieldset><legend><span class="label">Authors</span></legend>
904
+ # <ol><li>
905
+ # <label for="post_author_ids_1">
906
+ # <input name="post[author_ids][]" type="hidden" value="" />
907
+ # <input checked="checked" id="post_author_ids" name="post[author_ids][]"
908
+ # type="checkbox" value="1" /> Renan T. Fernandes
909
+ # </label>
910
+ # </li>
911
+ # ....
912
+ # </ol>
913
+ # </fieldset>
914
+ # </li>
915
+ # ....
916
+ #
917
+ # NOTE : Accept all radio options, plus :checked_value and :unchecked_value
918
+ # NOTE²: Don't change :(un)checkd_value unless you know what you're doing !
919
+ #
920
+ def check_boxes_input(method, options)
921
+ collection = find_collection_for_column(method, options)
922
+ html_options = set_options(options).merge(options.delete(:input_html) || {})
923
+
924
+ input_name = generate_association_input_name(method)
925
+ html_options = { :name => "#{@object_name}[#{input_name}][]" }.merge(html_options)
926
+ value_as_class = options.delete(:value_as_class)
927
+
928
+ list_item_content = collection.map do |c|
929
+ label = c.is_a?(Array) ? c.first : c
930
+ value = c.is_a?(Array) ? c.last : c
931
+
932
+ li_content = template.content_tag(:label,
933
+ "#{self.check_box(input_name, html_options,
934
+ options.delete(:checked_value) || value, options.delete(:unchecked_value) || '')
935
+ } #{label}", :for => generate_html_id(input_name, value.to_s.downcase)
936
+ )
937
+
938
+ li_options = value_as_class ? { :class => value.to_s.downcase } : {}
939
+ template.content_tag(:li, li_content, li_options)
940
+ end
941
+
942
+ field_set_and_list_wrapping_for_method(method, options, list_item_content)
943
+ end
944
+ alias :checkboxes_input :check_boxes_input
945
+ alias :check_box_input :check_boxes_input
946
+ alias :checkbox_input :check_boxes_input
947
+
948
+
949
+ # Outputs a label containing a checkbox and the label text. The label defaults
950
+ # to the column name (method name) and can be altered with the :label option.
951
+ #
952
+ # Different from other inputs, :required options has no effect here and
953
+ # :checked_value and :unchecked_value options are also available.
954
+ #
955
+ def boolean_input(method, options)
956
+ html_options = options.delete(:input_html) || {}
957
+
958
+ content = self.check_box(method, set_options(options).merge(html_options),
959
+ options.delete(:checked_value) || '1', options.delete(:unchecked_value) || '0')
960
+
961
+ # required does not make sense in check box
962
+ input_label(method, content + options.delete(:label), :skip_required => true)
963
+ end
964
+
965
+ # Generates an input for the given method using the type supplied with :as.
966
+ #
967
+ # If the input is included in INPUT_MAPPINGS, it uses input_simple
968
+ # implementation which maps most of the inputs. All others have specific
969
+ # code and then a proper handler should be called (like radio_input) for
970
+ # :radio types.
971
+ #
972
+ def inline_input_for(method, options)
973
+ input_type = options.delete(:as)
974
+
975
+ if INPUT_MAPPINGS.key?(input_type)
976
+ input_simple(input_type, method, options)
977
+ else
978
+ send("#{input_type}_input", method, options)
979
+ end
980
+ end
981
+
982
+ # Generates error messages for the given method. Errors can be shown as list
983
+ # or as sentence. If :none is set, no error is shown.
984
+ #
985
+ def inline_errors_for(method, options) #:nodoc:
986
+ return nil unless @object && @object.respond_to?(:errors) && [:sentence, :list].include?(@@inline_errors)
987
+
988
+ # Ruby 1.9: Strings are not Enumerable, ie no String#to_a
989
+ errors = @object.errors.on(method.to_s)
990
+ unless errors.respond_to?(:to_a)
991
+ errors = [errors]
992
+ else
993
+ errors = errors.to_a
994
+ end
995
+
996
+ send("error_#{@@inline_errors}", errors) unless errors.empty?
997
+ end
998
+
999
+ # Generates hints for the given method using the text supplied in :hint.
1000
+ #
1001
+ def inline_hints_for(method, options) #:nodoc:
1002
+ options[:hint].blank? ? '' : template.content_tag(:p, options[:hint], :class => 'inline-hints')
1003
+ end
1004
+
1005
+ # Creates an error sentence by calling to_sentence on the errors array.
1006
+ #
1007
+ def error_sentence(errors) #:nodoc:
1008
+ template.content_tag(:p, errors.to_sentence, :class => 'inline-errors')
1009
+ end
1010
+
1011
+ # Creates an error li list.
1012
+ #
1013
+ def error_list(errors) #:nodoc:
1014
+ list_elements = []
1015
+ errors.each do |error|
1016
+ list_elements << template.content_tag(:li, error)
1017
+ end
1018
+ template.content_tag(:ul, list_elements.join("\n"), :class => 'errors')
1019
+ end
1020
+
1021
+ # Generates the label for the input. Accepts the same options as Rails label
1022
+ # method and a fourth option that allows the label to be generated as span
1023
+ # with class label.
1024
+ #
1025
+ def input_label(method, text, options={}, as_span=false) #:nodoc:
1026
+ text << required_or_optional_string(options.delete(:required)) unless options.delete(:skip_required)
1027
+
1028
+ if as_span
1029
+ options[:class] ||= 'label'
1030
+ template.content_tag(:span, text, options)
1031
+ else
1032
+ self.label(method, text, options)
1033
+ end
1034
+ end
1035
+
1036
+ # Generates the required or optional string. If the value set is a proc,
1037
+ # it evaluates the proc first.
1038
+ #
1039
+ def required_or_optional_string(required) #:nodoc:
1040
+ string_or_proc = required ? @@required_string : @@optional_string
1041
+
1042
+ if string_or_proc.is_a? Proc
1043
+ string_or_proc.call
1044
+ else
1045
+ string_or_proc
1046
+ end
1047
+ end
1048
+
1049
+ # Generates a fieldset and wraps the content in an ordered list. When working
1050
+ # with nested attributes (in Rails 2.3), it allows %i as interpolation option
1051
+ # in :name. So you can do:
1052
+ #
1053
+ # f.inputs :name => 'Task #%i', :for => :tasks
1054
+ #
1055
+ # And it will generate a fieldset for each task with legend 'Task #1', 'Task #2',
1056
+ # 'Task #3' and so on.
1057
+ #
1058
+ def field_set_and_list_wrapping(html_options, contents='', &block) #:nodoc:
1059
+ legend = html_options.delete(:name).to_s
1060
+ legend %= parent_child_index(html_options[:parent]) if html_options[:parent]
1061
+ legend = template.content_tag(:legend, template.content_tag(:span, legend)) unless legend.blank?
1062
+
1063
+ contents = template.capture(&block) if block_given?
1064
+
1065
+ # Ruby 1.9: String#to_s behavior changed, need to make an explicit join.
1066
+ contents = contents.join if contents.respond_to?(:join)
1067
+ fieldset = template.content_tag(:fieldset,
1068
+ legend + template.content_tag(:ol, contents),
1069
+ html_options.except(:builder, :parent)
1070
+ )
1071
+
1072
+ template.concat(fieldset) if block_given?
1073
+ fieldset
1074
+ end
1075
+
1076
+ # Also generates a fieldset and an ordered list but with label based in
1077
+ # method. This methods is currently used by radio and datetime inputs.
1078
+ #
1079
+ def field_set_and_list_wrapping_for_method(method, options, contents)
1080
+ template.content_tag(:fieldset,
1081
+ %{<legend>#{input_label(method, options.delete(:label), options.slice(:required), true)}</legend>} +
1082
+ template.content_tag(:ol, contents)
1083
+ )
1084
+ end
1085
+
1086
+ # For methods that have a database column, take a best guess as to what the inout method
1087
+ # should be. In most cases, it will just return the column type (eg :string), but for special
1088
+ # cases it will simplify (like the case of :integer, :float & :decimal to :numeric), or do
1089
+ # something different (like :password and :select).
1090
+ #
1091
+ # If there is no column for the method (eg "virtual columns" with an attr_accessor), the
1092
+ # default is a :string, a similar behaviour to Rails' scaffolding.
1093
+ #
1094
+ def default_input_type(method) #:nodoc:
1095
+ return :string if @object.nil?
1096
+
1097
+ # Find the column object by attribute
1098
+ column = @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute)
1099
+
1100
+ # Associations map by default to a select
1101
+ return :select if column.nil? && find_reflection(method)
1102
+
1103
+ if column
1104
+ # handle the special cases where the column type doesn't map to an input method
1105
+ return :select if column.type == :integer && method.to_s =~ /_id$/
1106
+ return :datetime if column.type == :timestamp
1107
+ return :numeric if [:integer, :float, :decimal].include?(column.type)
1108
+ return :password if column.type == :string && method.to_s =~ /password/
1109
+ # otherwise assume the input name will be the same as the column type (eg string_input)
1110
+ return column.type
1111
+ else
1112
+ obj = @object.send(method) if @object.respond_to?(method)
1113
+
1114
+ return :file if obj && @@file_methods.any? { |m| obj.respond_to?(m) }
1115
+ return :password if method.to_s =~ /password/
1116
+ return :string
1117
+ end
1118
+ end
1119
+
1120
+ # Used by select and radio inputs. The collection can be retrieved by
1121
+ # three ways:
1122
+ #
1123
+ # * Explicitly provided through :collection
1124
+ # * Retrivied through an association
1125
+ # * Or a boolean column, which will generate a localized { "Yes" => true, "No" => false } hash.
1126
+ #
1127
+ # If the collection is not a hash or an array of strings, fixnums or arrays,
1128
+ # we use label_method and value_method to retreive an array with the
1129
+ # appropriate label and value.
1130
+ #
1131
+ def find_collection_for_column(column, options)
1132
+ reflection = find_reflection(column)
1133
+
1134
+ collection = if options[:collection]
1135
+ options.delete(:collection)
1136
+ elsif reflection || column.to_s =~ /_id$/
1137
+ parent_class = if reflection
1138
+ reflection.klass
1139
+ else
1140
+ ::ActiveSupport::Deprecation.warn("The _id way of doing things is deprecated. Please use the association method (#{column.to_s.sub(/_id$/,'')})", caller[3..-1])
1141
+ column.to_s.sub(/_id$/,'').camelize.constantize
1142
+ end
1143
+
1144
+ parent_class.find(:all)
1145
+ else
1146
+ create_boolean_collection(options)
1147
+ end
1148
+
1149
+ collection = collection.to_a if collection.instance_of?(Hash)
1150
+
1151
+ # Return if we have an Array of strings, fixnums or arrays
1152
+ return collection if collection.instance_of?(Array) &&
1153
+ [Array, Fixnum, String, Symbol].include?(collection.first.class)
1154
+
1155
+ label = options.delete(:label_method) || detect_label_method(collection)
1156
+ value = options.delete(:value_method) || :id
1157
+
1158
+ collection.map { |o| [o.send(label), o.send(value)] }
1159
+ end
1160
+
1161
+ # Detected the label collection method when none is supplied using the
1162
+ # values set in @@collection_label_methods.
1163
+ #
1164
+ def detect_label_method(collection) #:nodoc:
1165
+ @@collection_label_methods.detect { |m| collection.first.respond_to?(m) }
1166
+ end
1167
+
1168
+ # Returns a hash to be used by radio and select inputs when a boolean field
1169
+ # is provided.
1170
+ #
1171
+ def create_boolean_collection(options)
1172
+ options[:true] ||= I18n.t('yes', :default => 'Yes', :scope => [:formtastic])
1173
+ options[:false] ||= I18n.t('no', :default => 'No', :scope => [:formtastic])
1174
+ options[:value_as_class] = true unless options.key?(:value_as_class)
1175
+
1176
+ { options.delete(:true) => true, options.delete(:false) => false }
1177
+ end
1178
+
1179
+ # Used by association inputs (select, radio) to generate the name that should
1180
+ # be used for the input
1181
+ #
1182
+ # belongs_to :author; f.input :author; will generate 'author_id'
1183
+ # has_many :authors; f.input :authors; will generate 'author_ids'
1184
+ # has_and_belongs_to_many will act like has_many
1185
+ #
1186
+ def generate_association_input_name(method)
1187
+ if reflection = find_reflection(method)
1188
+ method = "#{method.to_s.singularize}_id"
1189
+ method = method.pluralize if [:has_and_belongs_to_many, :has_many].include?(reflection.macro)
1190
+ end
1191
+ method
1192
+ end
1193
+
1194
+ # If an association method is passed in (f.input :author) try to find the
1195
+ # reflection object.
1196
+ #
1197
+ def find_reflection(method)
1198
+ object.class.reflect_on_association(method) if object.class.respond_to?(:reflect_on_association)
1199
+ end
1200
+
1201
+ # Generates default_string_options by retrieving column information from
1202
+ # the database.
1203
+ #
1204
+ def default_string_options(method) #:nodoc:
1205
+ column = @object.column_for_attribute(method) if @object.respond_to?(:column_for_attribute)
1206
+
1207
+ if column.nil? || column.limit.nil?
1208
+ { :size => @@default_text_field_size }
1209
+ else
1210
+ { :maxlength => column.limit, :size => [column.limit, @@default_text_field_size].min }
1211
+ end
1212
+ end
1213
+
1214
+ # Generate the html id for the li tag.
1215
+ # It takes into account options[:index] and @auto_index to generate li
1216
+ # elements with appropriate index scope. It also sanitizes the object
1217
+ # and method names.
1218
+ #
1219
+ def generate_html_id(method_name, value='input')
1220
+ if options.has_key?(:index)
1221
+ index = "_#{options[:index]}"
1222
+ elsif defined?(@auto_index)
1223
+ index = "_#{@auto_index}"
1224
+ else
1225
+ index = ""
1226
+ end
1227
+ sanitized_method_name = method_name.to_s.sub(/\?$/,"")
1228
+
1229
+ "#{sanitized_object_name}#{index}_#{sanitized_method_name}_#{value}"
1230
+ end
1231
+
1232
+ # Gets the nested_child_index value from the parent builder. In Rails 2.3
1233
+ # it always returns a fixnum. In next versions it returns a hash with each
1234
+ # association that the parent builds.
1235
+ #
1236
+ def parent_child_index(parent)
1237
+ duck = parent[:builder].instance_variable_get('@nested_child_index')
1238
+
1239
+ if duck.is_a?(Hash)
1240
+ child = parent[:for]
1241
+ child = child.first if child.respond_to?(:first)
1242
+ duck[child].to_i + 1
1243
+ else
1244
+ duck.to_i + 1
1245
+ end
1246
+ end
1247
+
1248
+ def sanitized_object_name
1249
+ @sanitized_object_name ||= @object_name.to_s.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
1250
+ end
1251
+
1252
+ end
1253
+
1254
+
1255
+ # Wrappers around form_for (etc) with :builder => SemanticFormBuilder.
1256
+ #
1257
+ # * semantic_form_for(@post)
1258
+ # * semantic_fields_for(@post)
1259
+ # * semantic_form_remote_for(@post)
1260
+ # * semantic_remote_form_for(@post)
1261
+ #
1262
+ # Each of which are the equivalent of:
1263
+ #
1264
+ # * form_for(@post, :builder => Formtastic::SemanticFormBuilder))
1265
+ # * fields_for(@post, :builder => Formtastic::SemanticFormBuilder))
1266
+ # * form_remote_for(@post, :builder => Formtastic::SemanticFormBuilder))
1267
+ # * remote_form_for(@post, :builder => Formtastic::SemanticFormBuilder))
1268
+ #
1269
+ # Example Usage:
1270
+ #
1271
+ # <% semantic_form_for @post do |f| %>
1272
+ # <%= f.input :title %>
1273
+ # <%= f.input :body %>
1274
+ # <% end %>
1275
+ #
1276
+ # The above examples use a resource-oriented style of form_for() helper where only the @post
1277
+ # object is given as an argument, but the generic style is also supported if you really want it,
1278
+ # as is forms with inline objects (Post.new) rather than objects with instance variables (@post):
1279
+ #
1280
+ # <% semantic_form_for :post, @post, :url => posts_path do |f| %>
1281
+ # ...
1282
+ # <% end %>
1283
+ #
1284
+ # <% semantic_form_for :post, Post.new, :url => posts_path do |f| %>
1285
+ # ...
1286
+ # <% end %>
1287
+ #
1288
+ # The shorter, resource-oriented style is most definitely preferred, and has recieved the most
1289
+ # testing to date.
1290
+ #
1291
+ # Please note: Although it's possible to call Rails' built-in form_for() helper without an
1292
+ # object, all semantic forms *must* have an object (either Post.new or @post), as Formtastic
1293
+ # has too many dependencies on an ActiveRecord object being present.
1294
+ #
1295
+ module SemanticFormHelper
1296
+ @@builder = Formtastic::SemanticFormBuilder
1297
+
1298
+ # cattr_accessor :builder
1299
+ def self.builder=(val)
1300
+ @@builder = val
1301
+ end
1302
+
1303
+ [:form_for, :fields_for, :form_remote_for, :remote_form_for].each do |meth|
1304
+ src = <<-END_SRC
1305
+ def semantic_#{meth}(record_or_name_or_array, *args, &proc)
1306
+ options = args.extract_options!
1307
+ options[:builder] = @@builder
1308
+ options[:html] ||= {}
1309
+
1310
+ class_names = options[:html][:class] ? options[:html][:class].split(" ") : []
1311
+ class_names << "formtastic"
1312
+ class_names << case record_or_name_or_array
1313
+ when String, Symbol then record_or_name_or_array.to_s # :post => "post"
1314
+ when Array then record_or_name_or_array.last.class.to_s.underscore # [@post, @comment] # => "comment"
1315
+ else record_or_name_or_array.class.to_s.underscore # @post => "post"
1316
+ end
1317
+ options[:html][:class] = class_names.join(" ")
1318
+
1319
+ #{meth}(record_or_name_or_array, *(args << options), &proc)
1320
+ end
1321
+ END_SRC
1322
+ module_eval src, __FILE__, __LINE__
1323
+ end
1324
+ end
1325
+ end