actionview 4.1.0.beta1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of actionview might be problematic. Click here for more details.

Files changed (106) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +274 -0
  3. data/MIT-LICENSE +21 -0
  4. data/README.rdoc +34 -0
  5. data/lib/action_view.rb +97 -0
  6. data/lib/action_view/base.rb +205 -0
  7. data/lib/action_view/buffers.rb +49 -0
  8. data/lib/action_view/context.rb +36 -0
  9. data/lib/action_view/dependency_tracker.rb +93 -0
  10. data/lib/action_view/digestor.rb +116 -0
  11. data/lib/action_view/flows.rb +76 -0
  12. data/lib/action_view/helpers.rb +64 -0
  13. data/lib/action_view/helpers/active_model_helper.rb +49 -0
  14. data/lib/action_view/helpers/asset_tag_helper.rb +322 -0
  15. data/lib/action_view/helpers/asset_url_helper.rb +355 -0
  16. data/lib/action_view/helpers/atom_feed_helper.rb +203 -0
  17. data/lib/action_view/helpers/cache_helper.rb +200 -0
  18. data/lib/action_view/helpers/capture_helper.rb +216 -0
  19. data/lib/action_view/helpers/controller_helper.rb +25 -0
  20. data/lib/action_view/helpers/csrf_helper.rb +30 -0
  21. data/lib/action_view/helpers/date_helper.rb +1075 -0
  22. data/lib/action_view/helpers/debug_helper.rb +39 -0
  23. data/lib/action_view/helpers/form_helper.rb +1876 -0
  24. data/lib/action_view/helpers/form_options_helper.rb +843 -0
  25. data/lib/action_view/helpers/form_tag_helper.rb +746 -0
  26. data/lib/action_view/helpers/javascript_helper.rb +75 -0
  27. data/lib/action_view/helpers/number_helper.rb +425 -0
  28. data/lib/action_view/helpers/output_safety_helper.rb +38 -0
  29. data/lib/action_view/helpers/record_tag_helper.rb +108 -0
  30. data/lib/action_view/helpers/rendering_helper.rb +90 -0
  31. data/lib/action_view/helpers/sanitize_helper.rb +256 -0
  32. data/lib/action_view/helpers/tag_helper.rb +176 -0
  33. data/lib/action_view/helpers/tags.rb +41 -0
  34. data/lib/action_view/helpers/tags/base.rb +148 -0
  35. data/lib/action_view/helpers/tags/check_box.rb +64 -0
  36. data/lib/action_view/helpers/tags/checkable.rb +16 -0
  37. data/lib/action_view/helpers/tags/collection_check_boxes.rb +44 -0
  38. data/lib/action_view/helpers/tags/collection_helpers.rb +85 -0
  39. data/lib/action_view/helpers/tags/collection_radio_buttons.rb +36 -0
  40. data/lib/action_view/helpers/tags/collection_select.rb +28 -0
  41. data/lib/action_view/helpers/tags/color_field.rb +25 -0
  42. data/lib/action_view/helpers/tags/date_field.rb +13 -0
  43. data/lib/action_view/helpers/tags/date_select.rb +72 -0
  44. data/lib/action_view/helpers/tags/datetime_field.rb +22 -0
  45. data/lib/action_view/helpers/tags/datetime_local_field.rb +19 -0
  46. data/lib/action_view/helpers/tags/datetime_select.rb +8 -0
  47. data/lib/action_view/helpers/tags/email_field.rb +8 -0
  48. data/lib/action_view/helpers/tags/file_field.rb +8 -0
  49. data/lib/action_view/helpers/tags/grouped_collection_select.rb +29 -0
  50. data/lib/action_view/helpers/tags/hidden_field.rb +8 -0
  51. data/lib/action_view/helpers/tags/label.rb +65 -0
  52. data/lib/action_view/helpers/tags/month_field.rb +13 -0
  53. data/lib/action_view/helpers/tags/number_field.rb +18 -0
  54. data/lib/action_view/helpers/tags/password_field.rb +12 -0
  55. data/lib/action_view/helpers/tags/radio_button.rb +31 -0
  56. data/lib/action_view/helpers/tags/range_field.rb +8 -0
  57. data/lib/action_view/helpers/tags/search_field.rb +24 -0
  58. data/lib/action_view/helpers/tags/select.rb +41 -0
  59. data/lib/action_view/helpers/tags/tel_field.rb +8 -0
  60. data/lib/action_view/helpers/tags/text_area.rb +18 -0
  61. data/lib/action_view/helpers/tags/text_field.rb +29 -0
  62. data/lib/action_view/helpers/tags/time_field.rb +13 -0
  63. data/lib/action_view/helpers/tags/time_select.rb +8 -0
  64. data/lib/action_view/helpers/tags/time_zone_select.rb +20 -0
  65. data/lib/action_view/helpers/tags/url_field.rb +8 -0
  66. data/lib/action_view/helpers/tags/week_field.rb +13 -0
  67. data/lib/action_view/helpers/text_helper.rb +447 -0
  68. data/lib/action_view/helpers/translation_helper.rb +111 -0
  69. data/lib/action_view/helpers/url_helper.rb +625 -0
  70. data/lib/action_view/layouts.rb +426 -0
  71. data/lib/action_view/locale/en.yml +56 -0
  72. data/lib/action_view/log_subscriber.rb +44 -0
  73. data/lib/action_view/lookup_context.rb +249 -0
  74. data/lib/action_view/model_naming.rb +12 -0
  75. data/lib/action_view/path_set.rb +77 -0
  76. data/lib/action_view/railtie.rb +49 -0
  77. data/lib/action_view/record_identifier.rb +84 -0
  78. data/lib/action_view/renderer/abstract_renderer.rb +47 -0
  79. data/lib/action_view/renderer/partial_renderer.rb +492 -0
  80. data/lib/action_view/renderer/renderer.rb +50 -0
  81. data/lib/action_view/renderer/streaming_template_renderer.rb +103 -0
  82. data/lib/action_view/renderer/template_renderer.rb +96 -0
  83. data/lib/action_view/rendering.rb +145 -0
  84. data/lib/action_view/routing_url_for.rb +109 -0
  85. data/lib/action_view/tasks/dependencies.rake +17 -0
  86. data/lib/action_view/template.rb +340 -0
  87. data/lib/action_view/template/error.rb +141 -0
  88. data/lib/action_view/template/handlers.rb +53 -0
  89. data/lib/action_view/template/handlers/builder.rb +26 -0
  90. data/lib/action_view/template/handlers/erb.rb +145 -0
  91. data/lib/action_view/template/handlers/raw.rb +11 -0
  92. data/lib/action_view/template/resolver.rb +329 -0
  93. data/lib/action_view/template/text.rb +34 -0
  94. data/lib/action_view/template/types.rb +57 -0
  95. data/lib/action_view/test_case.rb +272 -0
  96. data/lib/action_view/testing/resolvers.rb +50 -0
  97. data/lib/action_view/vendor/html-scanner.rb +20 -0
  98. data/lib/action_view/vendor/html-scanner/html/document.rb +68 -0
  99. data/lib/action_view/vendor/html-scanner/html/node.rb +532 -0
  100. data/lib/action_view/vendor/html-scanner/html/sanitizer.rb +188 -0
  101. data/lib/action_view/vendor/html-scanner/html/selector.rb +830 -0
  102. data/lib/action_view/vendor/html-scanner/html/tokenizer.rb +107 -0
  103. data/lib/action_view/vendor/html-scanner/html/version.rb +11 -0
  104. data/lib/action_view/version.rb +11 -0
  105. data/lib/action_view/view_paths.rb +96 -0
  106. metadata +218 -0
@@ -0,0 +1,843 @@
1
+ require 'cgi'
2
+ require 'erb'
3
+ require 'action_view/helpers/form_helper'
4
+ require 'active_support/core_ext/string/output_safety'
5
+ require 'active_support/core_ext/array/extract_options'
6
+ require 'active_support/core_ext/array/wrap'
7
+
8
+ module ActionView
9
+ # = Action View Form Option Helpers
10
+ module Helpers
11
+ # Provides a number of methods for turning different kinds of containers into a set of option tags.
12
+ #
13
+ # The <tt>collection_select</tt>, <tt>select</tt> and <tt>time_zone_select</tt> methods take an <tt>options</tt> parameter, a hash:
14
+ #
15
+ # * <tt>:include_blank</tt> - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element.
16
+ #
17
+ # select("post", "category", Post::CATEGORIES, {include_blank: true})
18
+ #
19
+ # could become:
20
+ #
21
+ # <select name="post[category]">
22
+ # <option></option>
23
+ # <option>joke</option>
24
+ # <option>poem</option>
25
+ # </select>
26
+ #
27
+ # Another common case is a select tag for a <tt>belongs_to</tt>-associated object.
28
+ #
29
+ # Example with @post.person_id => 2:
30
+ #
31
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: 'None'})
32
+ #
33
+ # could become:
34
+ #
35
+ # <select name="post[person_id]">
36
+ # <option value="">None</option>
37
+ # <option value="1">David</option>
38
+ # <option value="2" selected="selected">Sam</option>
39
+ # <option value="3">Tobias</option>
40
+ # </select>
41
+ #
42
+ # * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string.
43
+ #
44
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person'})
45
+ #
46
+ # could become:
47
+ #
48
+ # <select name="post[person_id]">
49
+ # <option value="">Select Person</option>
50
+ # <option value="1">David</option>
51
+ # <option value="2">Sam</option>
52
+ # <option value="3">Tobias</option>
53
+ # </select>
54
+ #
55
+ # Like the other form helpers, +select+ can accept an <tt>:index</tt> option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this
56
+ # option to be in the +html_options+ parameter.
57
+ #
58
+ # select("album[]", "genre", %w[rap rock country], {}, { index: nil })
59
+ #
60
+ # becomes:
61
+ #
62
+ # <select name="album[][genre]" id="album__genre">
63
+ # <option value="rap">rap</option>
64
+ # <option value="rock">rock</option>
65
+ # <option value="country">country</option>
66
+ # </select>
67
+ #
68
+ # * <tt>:disabled</tt> - can be a single value or an array of values that will be disabled options in the final output.
69
+ #
70
+ # select("post", "category", Post::CATEGORIES, {disabled: 'restricted'})
71
+ #
72
+ # could become:
73
+ #
74
+ # <select name="post[category]">
75
+ # <option></option>
76
+ # <option>joke</option>
77
+ # <option>poem</option>
78
+ # <option disabled="disabled">restricted</option>
79
+ # </select>
80
+ #
81
+ # When used with the <tt>collection_select</tt> helper, <tt>:disabled</tt> can also be a Proc that identifies those options that should be disabled.
82
+ #
83
+ # collection_select(:post, :category_id, Category.all, :id, :name, {disabled: lambda{|category| category.archived? }})
84
+ #
85
+ # If the categories "2008 stuff" and "Christmas" return true when the method <tt>archived?</tt> is called, this would return:
86
+ # <select name="post[category_id]">
87
+ # <option value="1" disabled="disabled">2008 stuff</option>
88
+ # <option value="2" disabled="disabled">Christmas</option>
89
+ # <option value="3">Jokes</option>
90
+ # <option value="4">Poems</option>
91
+ # </select>
92
+ #
93
+ module FormOptionsHelper
94
+ # ERB::Util can mask some helpers like textilize. Make sure to include them.
95
+ include TextHelper
96
+
97
+ # Create a select tag and a series of contained option tags for the provided object and method.
98
+ # The option currently held by the object will be selected, provided that the object is available.
99
+ #
100
+ # There are two possible formats for the +choices+ parameter, corresponding to other helpers' output:
101
+ #
102
+ # * A flat collection (see +options_for_select+).
103
+ #
104
+ # * A nested collection (see +grouped_options_for_select+).
105
+ #
106
+ # For example:
107
+ #
108
+ # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true })
109
+ #
110
+ # would become:
111
+ #
112
+ # <select name="post[person_id]">
113
+ # <option value=""></option>
114
+ # <option value="1" selected="selected">David</option>
115
+ # <option value="2">Sam</option>
116
+ # <option value="3">Tobias</option>
117
+ # </select>
118
+ #
119
+ # assuming the associated person has ID 1.
120
+ #
121
+ # This can be used to provide a default set of options in the standard way: before rendering the create form, a
122
+ # new model instance is assigned the default options and bound to @model_name. Usually this model is not saved
123
+ # to the database. Instead, a second model object is created when the create request is received.
124
+ # This allows the user to submit a form page more than once with the expected results of creating multiple records.
125
+ # In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
126
+ #
127
+ # By default, <tt>post.person_id</tt> is the selected option. Specify <tt>selected: value</tt> to use a different selection
128
+ # or <tt>selected: nil</tt> to leave all options unselected. Similarly, you can specify values to be disabled in the option
129
+ # tags by specifying the <tt>:disabled</tt> option. This can either be a single value or an array of values to be disabled.
130
+ #
131
+ # A block can be passed to +select+ to customize how the options tags will be rendered. This
132
+ # is useful when the options tag has complex attributes.
133
+ #
134
+ # select(report, "campaign_ids") do
135
+ # available_campaigns.each do |c|
136
+ # content_tag(:option, c.name, value: c.id, data: { tags: c.tags.to_json })
137
+ # end
138
+ # end
139
+ #
140
+ # ==== Gotcha
141
+ #
142
+ # The HTML specification says when +multiple+ parameter passed to select and all options got deselected
143
+ # web browsers do not send any value to server. Unfortunately this introduces a gotcha:
144
+ # if an +User+ model has many +roles+ and have +role_ids+ accessor, and in the form that edits roles of the user
145
+ # the user deselects all roles from +role_ids+ multiple select box, no +role_ids+ parameter is sent. So,
146
+ # any mass-assignment idiom like
147
+ #
148
+ # @user.update(params[:user])
149
+ #
150
+ # wouldn't update roles.
151
+ #
152
+ # To prevent this the helper generates an auxiliary hidden field before
153
+ # every multiple select. The hidden field has the same name as multiple select and blank value.
154
+ #
155
+ # This way, the client either sends only the hidden field (representing
156
+ # the deselected multiple select box), or both fields. Since the HTML specification
157
+ # says key/value pairs have to be sent in the same order they appear in the
158
+ # form, and parameters extraction gets the last occurrence of any repeated
159
+ # key in the query string, that works for ordinary forms.
160
+ #
161
+ # In case if you don't want the helper to generate this hidden field you can specify
162
+ # <tt>include_hidden: false</tt> option.
163
+ #
164
+ def select(object, method, choices = nil, options = {}, html_options = {}, &block)
165
+ Tags::Select.new(object, method, self, choices, options, html_options, &block).render
166
+ end
167
+
168
+ # Returns <tt><select></tt> and <tt><option></tt> tags for the collection of existing return values of
169
+ # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
170
+ # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
171
+ # or <tt>:include_blank</tt> in the +options+ hash.
172
+ #
173
+ # The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are methods to be called on each member
174
+ # of +collection+. The return values are used as the +value+ attribute and contents of each
175
+ # <tt><option></tt> tag, respectively. They can also be any object that responds to +call+, such
176
+ # as a +proc+, that will be called for each member of the +collection+ to
177
+ # retrieve the value/text.
178
+ #
179
+ # Example object structure for use with this method:
180
+ #
181
+ # class Post < ActiveRecord::Base
182
+ # belongs_to :author
183
+ # end
184
+ #
185
+ # class Author < ActiveRecord::Base
186
+ # has_many :posts
187
+ # def name_with_initial
188
+ # "#{first_name.first}. #{last_name}"
189
+ # end
190
+ # end
191
+ #
192
+ # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
193
+ #
194
+ # collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true)
195
+ #
196
+ # If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
197
+ # <select name="post[author_id]">
198
+ # <option value="">Please select</option>
199
+ # <option value="1" selected="selected">D. Heinemeier Hansson</option>
200
+ # <option value="2">D. Thomas</option>
201
+ # <option value="3">M. Clark</option>
202
+ # </select>
203
+ def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
204
+ Tags::CollectionSelect.new(object, method, self, collection, value_method, text_method, options, html_options).render
205
+ end
206
+
207
+ # Returns <tt><select></tt>, <tt><optgroup></tt> and <tt><option></tt> tags for the collection of existing return values of
208
+ # +method+ for +object+'s class. The value returned from calling +method+ on the instance +object+ will
209
+ # be selected. If calling +method+ returns +nil+, no selection is made without including <tt>:prompt</tt>
210
+ # or <tt>:include_blank</tt> in the +options+ hash.
211
+ #
212
+ # Parameters:
213
+ # * +object+ - The instance of the class to be used for the select tag
214
+ # * +method+ - The attribute of +object+ corresponding to the select tag
215
+ # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
216
+ # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
217
+ # array of child objects representing the <tt><option></tt> tags.
218
+ # * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
219
+ # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
220
+ # * +option_key_method+ - The name of a method which, when called on a child object of a member of
221
+ # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
222
+ # * +option_value_method+ - The name of a method which, when called on a child object of a member of
223
+ # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
224
+ #
225
+ # Example object structure for use with this method:
226
+ #
227
+ # class Continent < ActiveRecord::Base
228
+ # has_many :countries
229
+ # # attribs: id, name
230
+ # end
231
+ #
232
+ # class Country < ActiveRecord::Base
233
+ # belongs_to :continent
234
+ # # attribs: id, name, continent_id
235
+ # end
236
+ #
237
+ # class City < ActiveRecord::Base
238
+ # belongs_to :country
239
+ # # attribs: id, name, country_id
240
+ # end
241
+ #
242
+ # Sample usage:
243
+ #
244
+ # grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name)
245
+ #
246
+ # Possible output:
247
+ #
248
+ # <select name="city[country_id]">
249
+ # <optgroup label="Africa">
250
+ # <option value="1">South Africa</option>
251
+ # <option value="3">Somalia</option>
252
+ # </optgroup>
253
+ # <optgroup label="Europe">
254
+ # <option value="7" selected="selected">Denmark</option>
255
+ # <option value="2">Ireland</option>
256
+ # </optgroup>
257
+ # </select>
258
+ #
259
+ def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
260
+ Tags::GroupedCollectionSelect.new(object, method, self, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options).render
261
+ end
262
+
263
+ # Returns select and option tags for the given object and method, using
264
+ # #time_zone_options_for_select to generate the list of option tags.
265
+ #
266
+ # In addition to the <tt>:include_blank</tt> option documented above,
267
+ # this method also supports a <tt>:model</tt> option, which defaults
268
+ # to ActiveSupport::TimeZone. This may be used by users to specify a
269
+ # different time zone model object. (See +time_zone_options_for_select+
270
+ # for more information.)
271
+ #
272
+ # You can also supply an array of ActiveSupport::TimeZone objects
273
+ # as +priority_zones+, so that they will be listed above the rest of the
274
+ # (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience
275
+ # for obtaining a list of the US time zones, or a Regexp to select the zones
276
+ # of your choice)
277
+ #
278
+ # Finally, this method supports a <tt>:default</tt> option, which selects
279
+ # a default ActiveSupport::TimeZone if the object's time zone is +nil+.
280
+ #
281
+ # time_zone_select( "user", "time_zone", nil, include_blank: true)
282
+ #
283
+ # time_zone_select( "user", "time_zone", nil, default: "Pacific Time (US & Canada)" )
284
+ #
285
+ # time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, default: "Pacific Time (US & Canada)")
286
+ #
287
+ # time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ])
288
+ #
289
+ # time_zone_select( "user", 'time_zone', /Australia/)
290
+ #
291
+ # time_zone_select( "user", "time_zone", ActiveSupport::TimeZone.all.sort, model: ActiveSupport::TimeZone)
292
+ def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
293
+ Tags::TimeZoneSelect.new(object, method, self, priority_zones, options, html_options).render
294
+ end
295
+
296
+ # Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
297
+ # where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
298
+ # the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
299
+ # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+
300
+ # may also be an array of values to be selected when using a multiple select.
301
+ #
302
+ # options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
303
+ # # => <option value="$">Dollar</option>
304
+ # # => <option value="DKK">Kroner</option>
305
+ #
306
+ # options_for_select([ "VISA", "MasterCard" ], "MasterCard")
307
+ # # => <option>VISA</option>
308
+ # # => <option selected="selected">MasterCard</option>
309
+ #
310
+ # options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
311
+ # # => <option value="$20">Basic</option>
312
+ # # => <option value="$40" selected="selected">Plus</option>
313
+ #
314
+ # options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
315
+ # # => <option selected="selected">VISA</option>
316
+ # # => <option>MasterCard</option>
317
+ # # => <option selected="selected">Discover</option>
318
+ #
319
+ # You can optionally provide html attributes as the last element of the array.
320
+ #
321
+ # options_for_select([ "Denmark", ["USA", {class: 'bold'}], "Sweden" ], ["USA", "Sweden"])
322
+ # # => <option value="Denmark">Denmark</option>
323
+ # # => <option value="USA" class="bold" selected="selected">USA</option>
324
+ # # => <option value="Sweden" selected="selected">Sweden</option>
325
+ #
326
+ # options_for_select([["Dollar", "$", {class: "bold"}], ["Kroner", "DKK", {onclick: "alert('HI');"}]])
327
+ # # => <option value="$" class="bold">Dollar</option>
328
+ # # => <option value="DKK" onclick="alert('HI');">Kroner</option>
329
+ #
330
+ # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value
331
+ # or array of values to be disabled. In this case, you can use <tt>:selected</tt> to specify selected option tags.
332
+ #
333
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: "Super Platinum")
334
+ # # => <option value="Free">Free</option>
335
+ # # => <option value="Basic">Basic</option>
336
+ # # => <option value="Advanced">Advanced</option>
337
+ # # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
338
+ #
339
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: ["Advanced", "Super Platinum"])
340
+ # # => <option value="Free">Free</option>
341
+ # # => <option value="Basic">Basic</option>
342
+ # # => <option value="Advanced" disabled="disabled">Advanced</option>
343
+ # # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
344
+ #
345
+ # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], selected: "Free", disabled: "Super Platinum")
346
+ # # => <option value="Free" selected="selected">Free</option>
347
+ # # => <option value="Basic">Basic</option>
348
+ # # => <option value="Advanced">Advanced</option>
349
+ # # => <option value="Super Platinum" disabled="disabled">Super Platinum</option>
350
+ #
351
+ # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.
352
+ def options_for_select(container, selected = nil)
353
+ return container if String === container
354
+
355
+ selected, disabled = extract_selected_and_disabled(selected).map do |r|
356
+ Array(r).map { |item| item.to_s }
357
+ end
358
+
359
+ container.map do |element|
360
+ html_attributes = option_html_attributes(element)
361
+ text, value = option_text_and_value(element).map { |item| item.to_s }
362
+
363
+ html_attributes[:selected] = option_value_selected?(value, selected)
364
+ html_attributes[:disabled] = disabled && option_value_selected?(value, disabled)
365
+ html_attributes[:value] = value
366
+
367
+ content_tag_string(:option, text, html_attributes)
368
+ end.join("\n").html_safe
369
+ end
370
+
371
+ # Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning
372
+ # the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
373
+ #
374
+ # options_from_collection_for_select(@people, 'id', 'name')
375
+ # # => <option value="#{person.id}">#{person.name}</option>
376
+ #
377
+ # This is more often than not used inside a #select_tag like this example:
378
+ #
379
+ # select_tag 'person', options_from_collection_for_select(@people, 'id', 'name')
380
+ #
381
+ # If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+
382
+ # will be selected option tag(s).
383
+ #
384
+ # If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous
385
+ # function are the selected values.
386
+ #
387
+ # +selected+ can also be a hash, specifying both <tt>:selected</tt> and/or <tt>:disabled</tt> values as required.
388
+ #
389
+ # Be sure to specify the same class as the +value_method+ when specifying selected or disabled options.
390
+ # Failure to do this will produce undesired results. Example:
391
+ # options_from_collection_for_select(@people, 'id', 'name', '1')
392
+ # Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string)
393
+ # options_from_collection_for_select(@people, 'id', 'name', 1)
394
+ # should produce the desired results.
395
+ def options_from_collection_for_select(collection, value_method, text_method, selected = nil)
396
+ options = collection.map do |element|
397
+ [value_for_collection(element, text_method), value_for_collection(element, value_method), option_html_attributes(element)]
398
+ end
399
+ selected, disabled = extract_selected_and_disabled(selected)
400
+ select_deselect = {
401
+ selected: extract_values_from_collection(collection, value_method, selected),
402
+ disabled: extract_values_from_collection(collection, value_method, disabled)
403
+ }
404
+
405
+ options_for_select(options, select_deselect)
406
+ end
407
+
408
+ # Returns a string of <tt><option></tt> tags, like <tt>options_from_collection_for_select</tt>, but
409
+ # groups them by <tt><optgroup></tt> tags based on the object relationships of the arguments.
410
+ #
411
+ # Parameters:
412
+ # * +collection+ - An array of objects representing the <tt><optgroup></tt> tags.
413
+ # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an
414
+ # array of child objects representing the <tt><option></tt> tags.
415
+ # * group_label_method+ - The name of a method which, when called on a member of +collection+, returns a
416
+ # string to be used as the +label+ attribute for its <tt><optgroup></tt> tag.
417
+ # * +option_key_method+ - The name of a method which, when called on a child object of a member of
418
+ # +collection+, returns a value to be used as the +value+ attribute for its <tt><option></tt> tag.
419
+ # * +option_value_method+ - The name of a method which, when called on a child object of a member of
420
+ # +collection+, returns a value to be used as the contents of its <tt><option></tt> tag.
421
+ # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
422
+ # which will have the +selected+ attribute set. Corresponds to the return value of one of the calls
423
+ # to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are
424
+ # to be specified.
425
+ #
426
+ # Example object structure for use with this method:
427
+ #
428
+ # class Continent < ActiveRecord::Base
429
+ # has_many :countries
430
+ # # attribs: id, name
431
+ # end
432
+ #
433
+ # class Country < ActiveRecord::Base
434
+ # belongs_to :continent
435
+ # # attribs: id, name, continent_id
436
+ # end
437
+ #
438
+ # Sample usage:
439
+ # option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
440
+ #
441
+ # Possible output:
442
+ # <optgroup label="Africa">
443
+ # <option value="1">Egypt</option>
444
+ # <option value="4">Rwanda</option>
445
+ # ...
446
+ # </optgroup>
447
+ # <optgroup label="Asia">
448
+ # <option value="3" selected="selected">China</option>
449
+ # <option value="12">India</option>
450
+ # <option value="5">Japan</option>
451
+ # ...
452
+ # </optgroup>
453
+ #
454
+ # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
455
+ # wrap the output in an appropriate <tt><select></tt> tag.
456
+ def option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
457
+ collection.map do |group|
458
+ option_tags = options_from_collection_for_select(
459
+ group.send(group_method), option_key_method, option_value_method, selected_key)
460
+
461
+ content_tag(:optgroup, option_tags, label: group.send(group_label_method))
462
+ end.join.html_safe
463
+ end
464
+
465
+ # Returns a string of <tt><option></tt> tags, like <tt>options_for_select</tt>, but
466
+ # wraps them with <tt><optgroup></tt> tags.
467
+ #
468
+ # Parameters:
469
+ # * +grouped_options+ - Accepts a nested array or hash of strings. The first value serves as the
470
+ # <tt><optgroup></tt> label while the second value must be an array of options. The second value can be a
471
+ # nested array of text-value pairs. See <tt>options_for_select</tt> for more info.
472
+ # Ex. ["North America",[["United States","US"],["Canada","CA"]]]
473
+ # * +selected_key+ - A value equal to the +value+ attribute for one of the <tt><option></tt> tags,
474
+ # which will have the +selected+ attribute set. Note: It is possible for this value to match multiple options
475
+ # as you might have the same option in multiple groups. Each will then get <tt>selected="selected"</tt>.
476
+ #
477
+ # Options:
478
+ # * <tt>:prompt</tt> - set to true or a prompt string. When the select element doesn't have a value yet, this
479
+ # prepends an option with a generic prompt - "Please select" - or the given prompt string.
480
+ # * <tt>:divider</tt> - the divider for the options groups.
481
+ #
482
+ # grouped_options = [
483
+ # ['North America',
484
+ # [['United States','US'],'Canada']],
485
+ # ['Europe',
486
+ # ['Denmark','Germany','France']]
487
+ # ]
488
+ # grouped_options_for_select(grouped_options)
489
+ #
490
+ # grouped_options = {
491
+ # 'North America' => [['United States','US'], 'Canada'],
492
+ # 'Europe' => ['Denmark','Germany','France']
493
+ # }
494
+ # grouped_options_for_select(grouped_options)
495
+ #
496
+ # Possible output:
497
+ # <optgroup label="North America">
498
+ # <option value="US">United States</option>
499
+ # <option value="Canada">Canada</option>
500
+ # </optgroup>
501
+ # <optgroup label="Europe">
502
+ # <option value="Denmark">Denmark</option>
503
+ # <option value="Germany">Germany</option>
504
+ # <option value="France">France</option>
505
+ # </optgroup>
506
+ #
507
+ # grouped_options = [
508
+ # [['United States','US'], 'Canada'],
509
+ # ['Denmark','Germany','France']
510
+ # ]
511
+ # grouped_options_for_select(grouped_options, nil, divider: '---------')
512
+ #
513
+ # Possible output:
514
+ # <optgroup label="---------">
515
+ # <option value="US">United States</option>
516
+ # <option value="Canada">Canada</option>
517
+ # </optgroup>
518
+ # <optgroup label="---------">
519
+ # <option value="Denmark">Denmark</option>
520
+ # <option value="Germany">Germany</option>
521
+ # <option value="France">France</option>
522
+ # </optgroup>
523
+ #
524
+ # <b>Note:</b> Only the <tt><optgroup></tt> and <tt><option></tt> tags are returned, so you still have to
525
+ # wrap the output in an appropriate <tt><select></tt> tag.
526
+ def grouped_options_for_select(grouped_options, selected_key = nil, options = {})
527
+ prompt = options[:prompt]
528
+ divider = options[:divider]
529
+
530
+ body = "".html_safe
531
+
532
+ if prompt
533
+ body.safe_concat content_tag(:option, prompt_text(prompt), value: "")
534
+ end
535
+
536
+ grouped_options.each do |container|
537
+ html_attributes = option_html_attributes(container)
538
+
539
+ if divider
540
+ label = divider
541
+ else
542
+ label, container = container
543
+ end
544
+
545
+ html_attributes = { label: label }.merge!(html_attributes)
546
+ body.safe_concat content_tag(:optgroup, options_for_select(container, selected_key), html_attributes)
547
+ end
548
+
549
+ body
550
+ end
551
+
552
+ # Returns a string of option tags for pretty much any time zone in the
553
+ # world. Supply a ActiveSupport::TimeZone name as +selected+ to have it
554
+ # marked as the selected option tag. You can also supply an array of
555
+ # ActiveSupport::TimeZone objects as +priority_zones+, so that they will
556
+ # be listed above the rest of the (long) list. (You can use
557
+ # ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list
558
+ # of the US time zones, or a Regexp to select the zones of your choice)
559
+ #
560
+ # The +selected+ parameter must be either +nil+, or a string that names
561
+ # a ActiveSupport::TimeZone.
562
+ #
563
+ # By default, +model+ is the ActiveSupport::TimeZone constant (which can
564
+ # be obtained in Active Record as a value object). The only requirement
565
+ # is that the +model+ parameter be an object that responds to +all+, and
566
+ # returns an array of objects that represent time zones.
567
+ #
568
+ # NOTE: Only the option tags are returned, you have to wrap this call in
569
+ # a regular HTML select tag.
570
+ def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
571
+ zone_options = "".html_safe
572
+
573
+ zones = model.all
574
+ convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } }
575
+
576
+ if priority_zones
577
+ if priority_zones.is_a?(Regexp)
578
+ priority_zones = zones.select { |z| z =~ priority_zones }
579
+ end
580
+
581
+ zone_options.safe_concat options_for_select(convert_zones[priority_zones], selected)
582
+ zone_options.safe_concat content_tag(:option, '-------------', value: '', disabled: true)
583
+ zone_options.safe_concat "\n"
584
+
585
+ zones = zones - priority_zones
586
+ end
587
+
588
+ zone_options.safe_concat options_for_select(convert_zones[zones], selected)
589
+ end
590
+
591
+ # Returns radio button tags for the collection of existing return values
592
+ # of +method+ for +object+'s class. The value returned from calling
593
+ # +method+ on the instance +object+ will be selected. If calling +method+
594
+ # returns +nil+, no selection is made.
595
+ #
596
+ # The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
597
+ # methods to be called on each member of +collection+. The return values
598
+ # are used as the +value+ attribute and contents of each radio button tag,
599
+ # respectively. They can also be any object that responds to +call+, such
600
+ # as a +proc+, that will be called for each member of the +collection+ to
601
+ # retrieve the value/text.
602
+ #
603
+ # Example object structure for use with this method:
604
+ # class Post < ActiveRecord::Base
605
+ # belongs_to :author
606
+ # end
607
+ # class Author < ActiveRecord::Base
608
+ # has_many :posts
609
+ # def name_with_initial
610
+ # "#{first_name.first}. #{last_name}"
611
+ # end
612
+ # end
613
+ #
614
+ # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
615
+ # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial)
616
+ #
617
+ # If <tt>@post.author_id</tt> is already <tt>1</tt>, this would return:
618
+ # <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" checked="checked" />
619
+ # <label for="post_author_id_1">D. Heinemeier Hansson</label>
620
+ # <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
621
+ # <label for="post_author_id_2">D. Thomas</label>
622
+ # <input id="post_author_id_3" name="post[author_id]" type="radio" value="3" />
623
+ # <label for="post_author_id_3">M. Clark</label>
624
+ #
625
+ # It is also possible to customize the way the elements will be shown by
626
+ # giving a block to the method:
627
+ # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
628
+ # b.label { b.radio_button }
629
+ # end
630
+ #
631
+ # The argument passed to the block is a special kind of builder for this
632
+ # collection, which has the ability to generate the label and radio button
633
+ # for the current item in the collection, with proper text and value.
634
+ # Using it, you can change the label and radio button display order or
635
+ # even use the label as wrapper, as in the example above.
636
+ #
637
+ # The builder methods <tt>label</tt> and <tt>radio_button</tt> also accept
638
+ # extra html options:
639
+ # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
640
+ # b.label(class: "radio_button") { b.radio_button(class: "radio_button") }
641
+ # end
642
+ #
643
+ # There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
644
+ # <tt>value</tt>, which are the current item being rendered, its text and value methods,
645
+ # respectively. You can use them like this:
646
+ # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b|
647
+ # b.label(:"data-value" => b.value) { b.radio_button + b.text }
648
+ # end
649
+ def collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
650
+ Tags::CollectionRadioButtons.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
651
+ end
652
+
653
+ # Returns check box tags for the collection of existing return values of
654
+ # +method+ for +object+'s class. The value returned from calling +method+
655
+ # on the instance +object+ will be selected. If calling +method+ returns
656
+ # +nil+, no selection is made.
657
+ #
658
+ # The <tt>:value_method</tt> and <tt>:text_method</tt> parameters are
659
+ # methods to be called on each member of +collection+. The return values
660
+ # are used as the +value+ attribute and contents of each check box tag,
661
+ # respectively. They can also be any object that responds to +call+, such
662
+ # as a +proc+, that will be called for each member of the +collection+ to
663
+ # retrieve the value/text.
664
+ #
665
+ # Example object structure for use with this method:
666
+ # class Post < ActiveRecord::Base
667
+ # has_and_belongs_to_many :authors
668
+ # end
669
+ # class Author < ActiveRecord::Base
670
+ # has_and_belongs_to_many :posts
671
+ # def name_with_initial
672
+ # "#{first_name.first}. #{last_name}"
673
+ # end
674
+ # end
675
+ #
676
+ # Sample usage (selecting the associated Author for an instance of Post, <tt>@post</tt>):
677
+ # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
678
+ #
679
+ # If <tt>@post.author_ids</tt> is already <tt>[1]</tt>, this would return:
680
+ # <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
681
+ # <label for="post_author_ids_1">D. Heinemeier Hansson</label>
682
+ # <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
683
+ # <label for="post_author_ids_2">D. Thomas</label>
684
+ # <input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
685
+ # <label for="post_author_ids_3">M. Clark</label>
686
+ # <input name="post[author_ids][]" type="hidden" value="" />
687
+ #
688
+ # It is also possible to customize the way the elements will be shown by
689
+ # giving a block to the method:
690
+ # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
691
+ # b.label { b.check_box }
692
+ # end
693
+ #
694
+ # The argument passed to the block is a special kind of builder for this
695
+ # collection, which has the ability to generate the label and check box
696
+ # for the current item in the collection, with proper text and value.
697
+ # Using it, you can change the label and check box display order or even
698
+ # use the label as wrapper, as in the example above.
699
+ #
700
+ # The builder methods <tt>label</tt> and <tt>check_box</tt> also accept
701
+ # extra html options:
702
+ # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
703
+ # b.label(class: "check_box") { b.check_box(class: "check_box") }
704
+ # end
705
+ #
706
+ # There are also three special methods available: <tt>object</tt>, <tt>text</tt> and
707
+ # <tt>value</tt>, which are the current item being rendered, its text and value methods,
708
+ # respectively. You can use them like this:
709
+ # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b|
710
+ # b.label(:"data-value" => b.value) { b.check_box + b.text }
711
+ # end
712
+ def collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
713
+ Tags::CollectionCheckBoxes.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block)
714
+ end
715
+
716
+ private
717
+ def option_html_attributes(element)
718
+ if Array === element
719
+ element.select { |e| Hash === e }.reduce({}, :merge!)
720
+ else
721
+ {}
722
+ end
723
+ end
724
+
725
+ def option_text_and_value(option)
726
+ # Options are [text, value] pairs or strings used for both.
727
+ if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
728
+ option = option.reject { |e| Hash === e } if Array === option
729
+ [option.first, option.last]
730
+ else
731
+ [option, option]
732
+ end
733
+ end
734
+
735
+ def option_value_selected?(value, selected)
736
+ Array(selected).include? value
737
+ end
738
+
739
+ def extract_selected_and_disabled(selected)
740
+ if selected.is_a?(Proc)
741
+ [selected, nil]
742
+ else
743
+ selected = Array.wrap(selected)
744
+ options = selected.extract_options!.symbolize_keys
745
+ selected_items = options.fetch(:selected, selected)
746
+ [selected_items, options[:disabled]]
747
+ end
748
+ end
749
+
750
+ def extract_values_from_collection(collection, value_method, selected)
751
+ if selected.is_a?(Proc)
752
+ collection.map do |element|
753
+ element.send(value_method) if selected.call(element)
754
+ end.compact
755
+ else
756
+ selected
757
+ end
758
+ end
759
+
760
+ def value_for_collection(item, value)
761
+ value.respond_to?(:call) ? value.call(item) : item.send(value)
762
+ end
763
+
764
+ def prompt_text(prompt)
765
+ prompt.kind_of?(String) ? prompt : I18n.translate('helpers.select.prompt', default: 'Please select')
766
+ end
767
+ end
768
+
769
+ class FormBuilder
770
+ # Wraps ActionView::Helpers::FormOptionsHelper#select for form builders:
771
+ #
772
+ # <%= form_for @post do |f| %>
773
+ # <%= f.select :person_id, Person.all.collect { |p| [ p.name, p.id ] }, include_blank: true %>
774
+ # <%= f.submit %>
775
+ # <% end %>
776
+ #
777
+ # Please refer to the documentation of the base helper for details.
778
+ def select(method, choices = nil, options = {}, html_options = {}, &block)
779
+ @template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options), &block)
780
+ end
781
+
782
+ # Wraps ActionView::Helpers::FormOptionsHelper#collection_select for form builders:
783
+ #
784
+ # <%= form_for @post do |f| %>
785
+ # <%= f.collection_select :person_id, Author.all, :id, :name_with_initial, prompt: true %>
786
+ # <%= f.submit %>
787
+ # <% end %>
788
+ #
789
+ # Please refer to the documentation of the base helper for details.
790
+ def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
791
+ @template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options))
792
+ end
793
+
794
+ # Wraps ActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders:
795
+ #
796
+ # <%= form_for @city do |f| %>
797
+ # <%= f.grouped_collection_select :country_id, @continents, :countries, :name, :id, :name %>
798
+ # <%= f.submit %>
799
+ # <% end %>
800
+ #
801
+ # Please refer to the documentation of the base helper for details.
802
+ def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
803
+ @template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options))
804
+ end
805
+
806
+ # Wraps ActionView::Helpers::FormOptionsHelper#time_zone_select for form builders:
807
+ #
808
+ # <%= form_for @user do |f| %>
809
+ # <%= f.time_zone_select :time_zone, nil, include_blank: true %>
810
+ # <%= f.submit %>
811
+ # <% end %>
812
+ #
813
+ # Please refer to the documentation of the base helper for details.
814
+ def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
815
+ @template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options))
816
+ end
817
+
818
+ # Wraps ActionView::Helpers::FormOptionsHelper#collection_check_boxes for form builders:
819
+ #
820
+ # <%= form_for @post do |f| %>
821
+ # <%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %>
822
+ # <%= f.submit %>
823
+ # <% end %>
824
+ #
825
+ # Please refer to the documentation of the base helper for details.
826
+ def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
827
+ @template.collection_check_boxes(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
828
+ end
829
+
830
+ # Wraps ActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders:
831
+ #
832
+ # <%= form_for @post do |f| %>
833
+ # <%= f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial %>
834
+ # <%= f.submit %>
835
+ # <% end %>
836
+ #
837
+ # Please refer to the documentation of the base helper for details.
838
+ def collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block)
839
+ @template.collection_radio_buttons(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block)
840
+ end
841
+ end
842
+ end
843
+ end