actionpack 0.9.0

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

Potentially problematic release.


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

Files changed (100) hide show
  1. data/CHANGELOG +604 -0
  2. data/MIT-LICENSE +21 -0
  3. data/README +418 -0
  4. data/RUNNING_UNIT_TESTS +14 -0
  5. data/examples/.htaccess +24 -0
  6. data/examples/address_book/index.rhtml +33 -0
  7. data/examples/address_book/layout.rhtml +8 -0
  8. data/examples/address_book_controller.cgi +9 -0
  9. data/examples/address_book_controller.fcgi +6 -0
  10. data/examples/address_book_controller.rb +52 -0
  11. data/examples/address_book_controller.rbx +4 -0
  12. data/examples/benchmark.rb +52 -0
  13. data/examples/benchmark_with_ar.fcgi +89 -0
  14. data/examples/blog_controller.cgi +53 -0
  15. data/examples/debate/index.rhtml +14 -0
  16. data/examples/debate/new_topic.rhtml +22 -0
  17. data/examples/debate/topic.rhtml +32 -0
  18. data/examples/debate_controller.cgi +57 -0
  19. data/install.rb +93 -0
  20. data/lib/action_controller.rb +47 -0
  21. data/lib/action_controller/assertions/action_pack_assertions.rb +166 -0
  22. data/lib/action_controller/assertions/active_record_assertions.rb +65 -0
  23. data/lib/action_controller/base.rb +626 -0
  24. data/lib/action_controller/benchmarking.rb +49 -0
  25. data/lib/action_controller/cgi_ext/cgi_ext.rb +43 -0
  26. data/lib/action_controller/cgi_ext/cgi_methods.rb +91 -0
  27. data/lib/action_controller/cgi_process.rb +123 -0
  28. data/lib/action_controller/filters.rb +279 -0
  29. data/lib/action_controller/flash.rb +65 -0
  30. data/lib/action_controller/layout.rb +143 -0
  31. data/lib/action_controller/request.rb +92 -0
  32. data/lib/action_controller/rescue.rb +94 -0
  33. data/lib/action_controller/response.rb +15 -0
  34. data/lib/action_controller/scaffolding.rb +183 -0
  35. data/lib/action_controller/session/active_record_store.rb +72 -0
  36. data/lib/action_controller/session/drb_server.rb +9 -0
  37. data/lib/action_controller/session/drb_store.rb +31 -0
  38. data/lib/action_controller/support/class_attribute_accessors.rb +57 -0
  39. data/lib/action_controller/support/class_inheritable_attributes.rb +37 -0
  40. data/lib/action_controller/support/clean_logger.rb +10 -0
  41. data/lib/action_controller/support/cookie_performance_fix.rb +121 -0
  42. data/lib/action_controller/support/inflector.rb +70 -0
  43. data/lib/action_controller/templates/rescues/_request_and_response.rhtml +28 -0
  44. data/lib/action_controller/templates/rescues/diagnostics.rhtml +22 -0
  45. data/lib/action_controller/templates/rescues/layout.rhtml +29 -0
  46. data/lib/action_controller/templates/rescues/missing_template.rhtml +2 -0
  47. data/lib/action_controller/templates/rescues/template_error.rhtml +26 -0
  48. data/lib/action_controller/templates/rescues/unknown_action.rhtml +2 -0
  49. data/lib/action_controller/templates/scaffolds/edit.rhtml +6 -0
  50. data/lib/action_controller/templates/scaffolds/layout.rhtml +29 -0
  51. data/lib/action_controller/templates/scaffolds/list.rhtml +24 -0
  52. data/lib/action_controller/templates/scaffolds/new.rhtml +5 -0
  53. data/lib/action_controller/templates/scaffolds/show.rhtml +9 -0
  54. data/lib/action_controller/test_process.rb +194 -0
  55. data/lib/action_controller/url_rewriter.rb +153 -0
  56. data/lib/action_view.rb +40 -0
  57. data/lib/action_view/base.rb +253 -0
  58. data/lib/action_view/helpers/active_record_helper.rb +171 -0
  59. data/lib/action_view/helpers/date_helper.rb +223 -0
  60. data/lib/action_view/helpers/debug_helper.rb +17 -0
  61. data/lib/action_view/helpers/form_helper.rb +176 -0
  62. data/lib/action_view/helpers/form_options_helper.rb +169 -0
  63. data/lib/action_view/helpers/tag_helper.rb +59 -0
  64. data/lib/action_view/helpers/text_helper.rb +129 -0
  65. data/lib/action_view/helpers/url_helper.rb +72 -0
  66. data/lib/action_view/partials.rb +61 -0
  67. data/lib/action_view/template_error.rb +84 -0
  68. data/lib/action_view/vendor/builder.rb +13 -0
  69. data/lib/action_view/vendor/builder/blankslate.rb +21 -0
  70. data/lib/action_view/vendor/builder/xmlbase.rb +143 -0
  71. data/lib/action_view/vendor/builder/xmlevents.rb +63 -0
  72. data/lib/action_view/vendor/builder/xmlmarkup.rb +288 -0
  73. data/rakefile +105 -0
  74. data/test/abstract_unit.rb +9 -0
  75. data/test/controller/action_pack_assertions_test.rb +295 -0
  76. data/test/controller/active_record_assertions_test.rb +118 -0
  77. data/test/controller/cgi_test.rb +142 -0
  78. data/test/controller/cookie_test.rb +38 -0
  79. data/test/controller/filters_test.rb +159 -0
  80. data/test/controller/flash_test.rb +69 -0
  81. data/test/controller/layout_test.rb +49 -0
  82. data/test/controller/redirect_test.rb +44 -0
  83. data/test/controller/render_test.rb +169 -0
  84. data/test/controller/url_test.rb +318 -0
  85. data/test/fixtures/layouts/builder.rxml +3 -0
  86. data/test/fixtures/layouts/standard.rhtml +1 -0
  87. data/test/fixtures/test/_customer.rhtml +1 -0
  88. data/test/fixtures/test/greeting.rhtml +1 -0
  89. data/test/fixtures/test/hello.rxml +4 -0
  90. data/test/fixtures/test/hello_world.rhtml +1 -0
  91. data/test/fixtures/test/hello_xml_world.rxml +11 -0
  92. data/test/fixtures/test/list.rhtml +1 -0
  93. data/test/template/active_record_helper_test.rb +76 -0
  94. data/test/template/date_helper_test.rb +103 -0
  95. data/test/template/form_helper_test.rb +115 -0
  96. data/test/template/form_options_helper_test.rb +174 -0
  97. data/test/template/tag_helper_test.rb +18 -0
  98. data/test/template/text_helper_test.rb +62 -0
  99. data/test/template/url_helper_test.rb +35 -0
  100. metadata +154 -0
@@ -0,0 +1,223 @@
1
+ require "date"
2
+
3
+ module ActionView
4
+ module Helpers
5
+ # The Date Helper primarily creates select/option tags for different kinds of dates and date elements. All of the select-type methods
6
+ # share a number of common options that are as follows:
7
+ #
8
+ # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday" would give
9
+ # birthday[month] instead of date[month] if passed to the select_month method.
10
+ # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
11
+ # * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true, the select_month
12
+ # method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead of "date[month]".
13
+ module DateHelper
14
+ DEFAULT_PREFIX = "date" unless const_defined?("DEFAULT_PREFIX")
15
+
16
+ # Reports the approximate distance in time between to Time objects. For example, if the distance is 47 minutes, it'll return
17
+ # "about 1 hour". See the source for the complete wording list.
18
+ def distance_of_time_in_words(from_time, to_time)
19
+ distance_in_minutes = ((to_time - from_time) / 60).round
20
+
21
+ case distance_in_minutes
22
+ when 0..45 then "#{distance_in_minutes} minutes"
23
+ when 46..90 then "about 1 hour"
24
+ when 90..1440 then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
25
+ when 1441..2880 then "1 day"
26
+ else "#{(distance_in_minutes / 1440).round} days"
27
+ end
28
+ end
29
+
30
+ # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute (identified by
31
+ # +method+) on an object assigned to the template (identified by +object+). It's possible to tailor the selects through the +options+ hash,
32
+ # which both accepts all the keys that each of the individual select builders does (like :use_month_numbers for select_month) and a range
33
+ # of discard options. The discard options are <tt>:discard_month</tt> and <tt>:discard_day</tt>. Set to true, they'll drop the respective
34
+ # select. Discarding the month select will also automatically discard the day select.
35
+ #
36
+ # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. Additionally, you can get the
37
+ # month select before the year by setting :month_before_year to true in the options. This is especially useful for credit card forms.
38
+ # Examples:
39
+ #
40
+ # date_select("post", "written_on")
41
+ # date_select("post", "written_on", :start_year => 1995)
42
+ # date_select("post", "written_on", :start_year => 1995, :use_month_numbers => true,
43
+ # :discard_day => true, :include_blank => true)
44
+ #
45
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
46
+ def date_select(object, method, options = {})
47
+ InstanceTag.new(object, method, self).to_date_select_tag(options)
48
+ end
49
+
50
+ # Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based
51
+ # attribute (identified by +method+) on an object assigned to the template (identified by +object+). Examples:
52
+ #
53
+ # datetime_select("post", "written_on")
54
+ # datetime_select("post", "written_on", :start_year => 1995)
55
+ #
56
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
57
+ def datetime_select(object, method, options = {})
58
+ InstanceTag.new(object, method, self).to_datetime_select_tag(options)
59
+ end
60
+
61
+ # Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
62
+ def select_date(date = Date.today, options = {})
63
+ select_year(date, options) + select_month(date, options) + select_day(date, options)
64
+ end
65
+
66
+ # Returns a set of html select-tags (one for year, month, day, hour, and minute) preselected the +datetime+.
67
+ def select_datetime(datetime = Time.now, options = {})
68
+ select_year(datetime, options) + select_month(datetime, options) + select_day(datetime, options) +
69
+ select_hour(datetime, options) + select_minute(datetime, options)
70
+ end
71
+
72
+ # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
73
+ # The <tt>minute</tt> can also be substituted for a minute number.
74
+ def select_minute(datetime, options = {})
75
+ minute_options = []
76
+
77
+ 0.upto(59) do |minute|
78
+ minute_options << ((datetime.kind_of?(Fixnum) ? datetime : datetime.min) == minute ?
79
+ "<option selected=\"selected\">#{leading_zero_on_single_digits(minute)}</option>\n" :
80
+ "<option>#{leading_zero_on_single_digits(minute)}</option>\n"
81
+ )
82
+ end
83
+
84
+ select_html("minute", minute_options, options[:prefix], options[:include_blank], options[:discard_type])
85
+ end
86
+
87
+ # Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
88
+ # The <tt>hour</tt> can also be substituted for a hour number.
89
+ def select_hour(datetime, options = {})
90
+ hour_options = []
91
+
92
+ 0.upto(23) do |hour|
93
+ hour_options << ((datetime.kind_of?(Fixnum) ? datetime : datetime.hour) == hour ?
94
+ "<option selected=\"selected\">#{leading_zero_on_single_digits(hour)}</option>\n" :
95
+ "<option>#{leading_zero_on_single_digits(hour)}</option>\n"
96
+ )
97
+ end
98
+
99
+ select_html("hour", hour_options, options[:prefix], options[:include_blank], options[:discard_type])
100
+ end
101
+
102
+ # Returns a select tag with options for each of the days 1 through 31 with the current day selected.
103
+ # The <tt>date</tt> can also be substituted for a hour number.
104
+ def select_day(date, options = {})
105
+ day_options = []
106
+
107
+ 1.upto(31) do |day|
108
+ day_options << ((date.kind_of?(Fixnum) ? date : date.day) == day ?
109
+ "<option selected=\"selected\">#{day}</option>\n" :
110
+ "<option>#{day}</option>\n"
111
+ )
112
+ end
113
+
114
+ select_html("day", day_options, options[:prefix], options[:include_blank], options[:discard_type])
115
+ end
116
+
117
+ # Returns a select tag with options for each of the months January through December with the current month selected.
118
+ # The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are used as values
119
+ # (what's submitted to the server). It's also possible to use month numbers for the presentation instead of names --
120
+ # set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you want both numbers and names,
121
+ # set the <tt>:add_month_numbers</tt> key in +options+ to true. Examples:
122
+ #
123
+ # select_month(Date.today) # Will use keys like "January", "March"
124
+ # select_month(Date.today, :use_month_numbers => true) # Will use keys like "1", "3"
125
+ # select_month(Date.today, :add_month_numbers => true) # Will use keys like "1 - January", "3 - March"
126
+ def select_month(date, options = {})
127
+ month_options = []
128
+
129
+ 1.upto(12) do |month_number|
130
+ month_name = if options[:use_month_numbers]
131
+ month_number
132
+ elsif options[:add_month_numbers]
133
+ month_number.to_s + " - " + Date::MONTHNAMES[month_number]
134
+ else
135
+ Date::MONTHNAMES[month_number]
136
+ end
137
+
138
+ month_options << ((date.kind_of?(Fixnum) ? date : date.month) == month_number ?
139
+ "<option value='#{month_number}' selected=\"selected\">#{month_name}</option>\n" :
140
+ "<option value='#{month_number}'>#{month_name}</option>\n"
141
+ )
142
+ end
143
+
144
+ select_html("month", month_options, options[:prefix], options[:include_blank], options[:discard_type])
145
+ end
146
+
147
+ # Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius
148
+ # can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the +options+. The <tt>date</tt> can also be substituted
149
+ # for a year given as a number. Example:
150
+ #
151
+ # select_year(Date.today, :start_year => 1992, :end_year => 2007)
152
+ def select_year(date, options = {})
153
+ year_options = []
154
+ unless date.kind_of?(Fixnum) then default_start_year, default_end_year = date.year - 5, date.year + 5 end
155
+
156
+ (options[:start_year] || default_start_year).upto(options[:end_year] || default_end_year) do |year|
157
+ year_options << ((date.kind_of?(Fixnum) ? date : date.year) == year ?
158
+ "<option selected=\"selected\">#{year}</option>\n" :
159
+ "<option>#{year}</option>\n"
160
+ )
161
+ end
162
+
163
+ select_html("year", year_options, options[:prefix], options[:include_blank], options[:discard_type])
164
+ end
165
+
166
+ private
167
+ def select_html(type, options, prefix = nil, include_blank = false, discard_type = false)
168
+ select_html = "<select name='#{prefix || DEFAULT_PREFIX}"
169
+ select_html << "[#{type}]" unless discard_type
170
+ select_html << "'>\n"
171
+ select_html << "<option></option>\n" if include_blank
172
+ select_html << options.to_s
173
+ select_html << "</select>\n"
174
+
175
+ return select_html
176
+ end
177
+
178
+ def leading_zero_on_single_digits(number)
179
+ number > 9 ? number : "0#{number}"
180
+ end
181
+ end
182
+
183
+ class InstanceTag #:nodoc:
184
+ include DateHelper
185
+
186
+ def to_date_select_tag(options = {})
187
+ defaults = { :discard_type => true }
188
+ options = defaults.merge(options)
189
+ options_with_prefix = Proc.new { |position| options.update({ :prefix => "#{@object_name}[#{@method_name}(#{position}i)]" }) }
190
+ date = options[:include_blank] ? (value || 0) : (value || Date.today)
191
+
192
+ date_select = ""
193
+
194
+ if options[:month_before_year]
195
+ date_select << select_month(date, options_with_prefix.call(2)) unless options[:discard_month]
196
+ date_select << select_year(date, options_with_prefix.call(1))
197
+ else
198
+ date_select << select_year(date, options_with_prefix.call(1))
199
+ date_select << select_month(date, options_with_prefix.call(2)) unless options[:discard_month]
200
+ end
201
+
202
+ date_select << select_day(date, options_with_prefix.call(3)) unless options[:discard_day] || options[:discard_month]
203
+
204
+ return date_select
205
+ end
206
+
207
+ def to_datetime_select_tag(options = {})
208
+ defaults = { :discard_type => true }
209
+ options = defaults.merge(options)
210
+ options_with_prefix = Proc.new { |position| options.update({ :prefix => "#{@object_name}[#{@method_name}(#{position}i)]" }) }
211
+ datetime = options[:include_blank] ? (value || 0) : (value || Time.now)
212
+
213
+ datetime_select = select_year(datetime, options_with_prefix.call(1))
214
+ datetime_select << select_month(datetime, options_with_prefix.call(2)) unless options[:discard_month]
215
+ datetime_select << select_day(datetime, options_with_prefix.call(3)) unless options[:discard_day] || options[:discard_month]
216
+ datetime_select << " &mdash; " + select_hour(datetime, options_with_prefix.call(4)) unless options[:discard_hour]
217
+ datetime_select << " : " + select_minute(datetime, options_with_prefix.call(5)) unless options[:discard_minute] || options[:discard_hour]
218
+
219
+ return datetime_select
220
+ end
221
+ end
222
+ end
223
+ end
@@ -0,0 +1,17 @@
1
+ module ActionView
2
+ module Helpers
3
+ # Provides a set of methods for making it easier to locate problems.
4
+ module DebugHelper
5
+ # Returns a <pre>-tag set with the +object+ dumped by YAML. Very readable way to inspect an object.
6
+ def debug(object)
7
+ begin
8
+ Marshal::dump(object)
9
+ "<pre class='debug_dump'>#{h(object.to_yaml).gsub(" ", "&nbsp; ")}</pre>"
10
+ rescue Object => e
11
+ # Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
12
+ "<code class='debug_dump'>#{h(object.inspect)}</code>"
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,176 @@
1
+ require 'cgi'
2
+ require File.dirname(__FILE__) + '/date_helper'
3
+ require File.dirname(__FILE__) + '/tag_helper'
4
+
5
+ module ActionView
6
+ module Helpers
7
+ # Provides a set of methods for working with forms and especially forms related to objects assigned to the template.
8
+ # The following is an example of a complete form for a person object that works for both creates and updates built
9
+ # with all the form helpers. The <tt>@person</tt> object was assigned by an action on the controller:
10
+ # <form action="save_person" method="post">
11
+ # Name:
12
+ # <%= text_field "person", "name", "size" => 20 %>
13
+ #
14
+ # Password:
15
+ # <%= password_field "person", "password", "maxsize" => 20 %>
16
+ #
17
+ # Single?:
18
+ # <%= check_box "person", "single" %>
19
+ #
20
+ # Description:
21
+ # <%= text_area "person", "description", "cols" => 20 %>
22
+ #
23
+ # <input type="submit" value="Save">
24
+ # </form>
25
+ #
26
+ # ...is compiled to:
27
+ #
28
+ # <form action="save_person" method="post">
29
+ # Name:
30
+ # <input type="text" id="person_name" name="person[name]"
31
+ # size="20" value="<%= @person.name %>" />
32
+ #
33
+ # Password:
34
+ # <input type="password" id="person_password" name="person[password]"
35
+ # size="20" maxsize="20" value="<%= @person.password %>" />
36
+ #
37
+ # Single?:
38
+ # <input type="checkbox" id="person_single" name="person[single] value="1" />
39
+ #
40
+ # Description:
41
+ # <textarea cols="20" rows="40" id="person_description" name="person[description]">
42
+ # <%= @person.description %>
43
+ # </textarea>
44
+ #
45
+ # <input type="submit" value="Save">
46
+ # </form>
47
+ #
48
+ # There's also methods for helping to build form tags in link:classes/ActionView/Helpers/FormOptionsHelper.html,
49
+ # link:classes/ActionView/Helpers/DateHelper.html, and link:classes/ActionView/Helpers/ActiveRecordHelper.html
50
+ module FormHelper
51
+ # Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object
52
+ # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
53
+ # hash with +options+.
54
+ #
55
+ # Examples (call, result):
56
+ # text_field("post", "title", "size" => 20)
57
+ # <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />
58
+ def text_field(object, method, options = {})
59
+ InstanceTag.new(object, method, self).to_input_field_tag("text", options)
60
+ end
61
+
62
+ # Works just like text_field, but returns a input tag of the "password" type instead.
63
+ def password_field(object, method, options = {})
64
+ InstanceTag.new(object, method, self).to_input_field_tag("password", options)
65
+ end
66
+
67
+ # Works just like text_field, but returns a input tag of the "hidden" type instead.
68
+ def hidden_field(object, method, options = {})
69
+ InstanceTag.new(object, method, self).to_input_field_tag("hidden", options)
70
+ end
71
+
72
+ # Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+)
73
+ # on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a
74
+ # hash with +options+.
75
+ #
76
+ # Example (call, result):
77
+ # text_area("post", "body", "cols" => 20, "rows" => 40)
78
+ # <textarea cols="20" rows="40" id="post_body" name="post[body]">
79
+ # #{@post.body}
80
+ # </textarea>
81
+ def text_area(object, method, options = {})
82
+ InstanceTag.new(object, method, self).to_text_area_tag(options)
83
+ end
84
+
85
+ # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object
86
+ # assigned to the template (identified by +object+). It's intended that +method+ returns an integer and if that
87
+ # integer is above zero, then the checkbox is checked. Additional options on the input tag can be passed as a
88
+ # hash with +options+. The +value+ defaults to 1, which is convenient for boolean values.
89
+ #
90
+ # Example (call, result). Imagine that @post.validated? returns 1:
91
+ # check_box("post", "validated")
92
+ # <input type="checkbox" id="post_validate" name="post[validated] value="1" checked="checked" />
93
+ def check_box(object, method, options = {}, value = "1")
94
+ InstanceTag.new(object, method, self).to_check_box_tag(options, value)
95
+ end
96
+ end
97
+
98
+ class InstanceTag #:nodoc:
99
+ include Helpers::TagHelper
100
+
101
+ attr_reader :method_name, :object_name
102
+
103
+ DEFAULT_FIELD_OPTIONS = { "size" => 30 } unless const_defined?("DEFAULT_FIELD_OPTIONS")
104
+ DEFAULT_TEXT_AREA_OPTIONS = { "wrap" => "virtual", "cols" => 40, "rows" => 20 } unless const_defined?("DEFAULT_TEXT_AREA_OPTIONS")
105
+
106
+ def initialize(object_name, method_name, template_object, local_binding = nil)
107
+ @object_name, @method_name = object_name, method_name
108
+ @template_object, @local_binding = template_object, local_binding
109
+ end
110
+
111
+ def to_input_field_tag(field_type, options = {})
112
+ html_options = DEFAULT_FIELD_OPTIONS.merge(options)
113
+ html_options.merge!({ "size" => options["maxlength"]}) if options["maxlength"] && !options["size"]
114
+ html_options.merge!({ "type" => field_type, "value" => value.to_s })
115
+ add_default_name_and_id(html_options)
116
+ tag("input", html_options)
117
+ end
118
+
119
+ def to_text_area_tag(options = {})
120
+ options = DEFAULT_TEXT_AREA_OPTIONS.merge(options)
121
+ add_default_name_and_id(options)
122
+ content_tag("textarea", html_escape(value), options)
123
+ end
124
+
125
+ def to_check_box_tag(options = {}, checked_value = "1")
126
+ options.merge!({"checked" => "checked"}) if !value.nil? && ((value.is_a?(TrueClass) || value.is_a?(FalseClass)) ? value : value.to_i > 0)
127
+ options.merge!({ "type" => "checkbox", "value" => checked_value })
128
+ add_default_name_and_id(options)
129
+ tag("input", options)
130
+ end
131
+
132
+ def to_date_tag()
133
+ defaults = { "discard_type" => true }
134
+ date = value || Date.today
135
+ options = Proc.new { |position| defaults.update({ :prefix => "#{@object_name}[#{@method_name}(#{position}i)]" }) }
136
+
137
+ html_day_select(date, options.call(3)) +
138
+ html_month_select(date, options.call(2)) +
139
+ html_year_select(date, options.call(1))
140
+ end
141
+
142
+ def to_boolean_select_tag(options = {})
143
+ add_default_name_and_id(options)
144
+ tag_text = "<select"
145
+ tag_text << tag_options(options)
146
+ tag_text << "><option value=\"false\""
147
+ tag_text << " selected" if value == false
148
+ tag_text << ">False</option><option value=\"true\""
149
+ tag_text << " selected" if value
150
+ tag_text << ">True</option></select>"
151
+ end
152
+
153
+ def object
154
+ @template_object.instance_variable_get "@#{@object_name}"
155
+ end
156
+
157
+ def value
158
+ object.send(@method_name) unless object.nil?
159
+ end
160
+
161
+ private
162
+ def add_default_name_and_id(options)
163
+ options['name'] = tag_name unless options.has_key? "name"
164
+ options['id'] = tag_id unless options.has_key? "id"
165
+ end
166
+
167
+ def tag_name
168
+ "#{@object_name}[#{@method_name}]"
169
+ end
170
+
171
+ def tag_id
172
+ "#{@object_name}_#{@method_name}"
173
+ end
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,169 @@
1
+ require 'cgi'
2
+ require 'erb'
3
+ require File.dirname(__FILE__) + '/form_helper'
4
+
5
+ module ActionView
6
+ module Helpers
7
+ # Provides a number of methods for turning different kinds of containers into a set of option tags. Neither of the methods provide
8
+ # the actual select tag, so you'll need to construct that in HTML manually.
9
+ module FormOptionsHelper
10
+ include ERB::Util
11
+
12
+ def select(object, method, choices, options = {}, html_options = {})
13
+ InstanceTag.new(object, method, self).to_select_tag(choices, options, html_options)
14
+ end
15
+
16
+ def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
17
+ InstanceTag.new(object, method, self).to_collection_select_tag(collection, value_method, text_method, options, html_options)
18
+ end
19
+
20
+ def country_select(object, method, priority_countries = nil, options = {}, html_options = {})
21
+ InstanceTag.new(object, method, self).to_country_select_tag(priority_countries, options, html_options)
22
+ end
23
+
24
+ # Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container
25
+ # where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and
26
+ # the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values
27
+ # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +Selected+
28
+ # may also be an array of values to be selected when using a multiple select.
29
+ #
30
+ # Examples (call, result):
31
+ # options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
32
+ # <option value="$">Dollar</option>\n<option value="DKK">Kroner</option>
33
+ #
34
+ # options_for_select([ "VISA", "Mastercard" ], "Mastercard")
35
+ # <option>VISA</option>\n<option selected="selected">Mastercard</option>
36
+ #
37
+ # options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
38
+ # <option value="$20">Basic</option>\n<option value="$40" selected="selected">Plus</option>
39
+ #
40
+ # options_for_select([ "VISA", "Mastercard", "Discover" ], ["VISA", "Discover"])
41
+ # <option selected="selected">VISA</option>\n<option>Mastercard</option>\n<option selected="selected">Discover</option>
42
+ def options_for_select(container, selected = nil)
43
+ container = container.to_a if Hash === container
44
+
45
+ options_for_select = container.inject([]) do |options, element|
46
+ if element.respond_to?(:first) && element.respond_to?(:last)
47
+ is_selected = ( (selected.respond_to?(:include?) ? selected.include?(element.last) : element.last == selected) )
48
+ if is_selected
49
+ options << "<option value=\"#{html_escape(element.last.to_s)}\" selected=\"selected\">#{html_escape(element.first.to_s)}</option>"
50
+ else
51
+ options << "<option value=\"#{html_escape(element.last.to_s)}\">#{html_escape(element.first.to_s)}</option>"
52
+ end
53
+ else
54
+ is_selected = ( (selected.respond_to?(:include?) ? selected.include?(element) : element == selected) )
55
+ options << ((is_selected) ? "<option selected=\"selected\">#{html_escape(element.to_s)}</option>" : "<option>#{html_escape(element.to_s)}</option>")
56
+ end
57
+ end
58
+
59
+ options_for_select.join("\n")
60
+ end
61
+
62
+ # Returns a string of option tags that has been compiled by iterating over the +collection+ and assigning the
63
+ # the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
64
+ # If +selected_value+ is specified, the element returning a match on +value_method+ will get the selected option tag.
65
+ #
66
+ # Example (call, result). Imagine a loop iterating over each +person+ in <tt>@project.people</tt> to generate a input tag:
67
+ # options_from_collection_for_select(@project.people, "id", "name")
68
+ # <option value="#{person.id}">#{person.name}</option>
69
+ def options_from_collection_for_select(collection, value_method, text_method, selected_value = nil)
70
+ options_for_select(
71
+ collection.inject([]) { |options, object| options << [ object.send(text_method), object.send(value_method) ] },
72
+ selected_value
73
+ )
74
+ end
75
+
76
+ # Returns a string of option tags, like options_from_collection_for_select, but surrounds them by <optgroup> tags.
77
+ #
78
+ # An array of group objects are passed. Each group should return an array of options when calling group_method
79
+ # Each group should should return its name when calling group_label_method.
80
+ #
81
+ # html_option_groups_from_collection(@continents, "countries", "contient_name", "country_id", "country_name", @selected_country.id)
82
+ #
83
+ # Could become:
84
+ # <optgroup label="Africa">
85
+ # <select>Egypt</select>
86
+ # <select>Rwanda</select>
87
+ # ...
88
+ # </optgroup>
89
+ # <optgroup label="Asia">
90
+ # <select>China</select>
91
+ # <select>India</select>
92
+ # <select>Japan</select>
93
+ # ...
94
+ # </optgroup>
95
+ #
96
+ # with objects of the following classes:
97
+ # class Continent
98
+ # def initialize(p_name, p_countries) @continent_name = p_name; @countries = p_countries; end
99
+ # def continent_name() @continent_name; end
100
+ # def countries() @countries; end
101
+ # end
102
+ # class Country
103
+ # def initialize(id, name) @id = id; @name = name end
104
+ # def country_id() @id; end
105
+ # def country_name() @name; end
106
+ # end
107
+ def option_groups_from_collection_for_select(collection, group_method, group_label_method,
108
+ option_key_method, option_value_method, selected_key = nil)
109
+ collection.inject("") do |options_for_select, group|
110
+ group_label_string = eval("group.#{group_label_method}")
111
+ options_for_select += "<optgroup label=\"#{html_escape(group_label_string)}\">"
112
+ options_for_select += options_from_collection_for_select(eval("group.#{group_method}"), option_key_method, option_value_method, selected_key)
113
+ options_for_select += '</optgroup>'
114
+ end
115
+ end
116
+
117
+ # Returns a string of option tags for pretty much any country in the world. Supply a country name as +selected+ to
118
+ # have it marked as the selected option tag. You can also supply an array of countries as +priority_countries+, so
119
+ # that they will be listed above the rest of the (long) list.
120
+ def country_options_for_select(selected = nil, priority_countries = nil)
121
+ country_options = ""
122
+
123
+ if priority_countries
124
+ country_options += options_for_select(priority_countries, selected)
125
+ country_options += "<option>-------------</option>\n"
126
+ end
127
+
128
+ if priority_countries && priority_countries.include?(selected)
129
+ country_options += options_for_select(COUNTRIES - priority_countries, selected)
130
+ else
131
+ country_options += options_for_select(COUNTRIES, selected)
132
+ end
133
+
134
+ return country_options
135
+ end
136
+
137
+
138
+ private
139
+ # All the countries included in the country_options output.
140
+ COUNTRIES = [ "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua And Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burma", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the", "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "England", "Equatorial Guinea", "Eritrea", "Espana", "Estonia", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Great Britain", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Republic of", "Korea (South)", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Ireland", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russia", "Russian Federation", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa (Independent)", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Scotland", "Senegal", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Suriname", "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City State (Holy See)", "Venezuela", "Viet Nam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wales", "Wallis and Futuna Islands", "Western Sahara", "Yemen", "Zambia", "Zimbabwe" ] unless const_defined?("COUNTRIES")
141
+ end
142
+
143
+ class InstanceTag #:nodoc:
144
+ include FormOptionsHelper
145
+
146
+ def to_select_tag(choices, options, html_options)
147
+ add_default_name_and_id(html_options)
148
+ content_tag("select", add_blank_option(options_for_select(choices, value), options[:include_blank]), html_options)
149
+ end
150
+
151
+ def to_collection_select_tag(collection, value_method, text_method, options, html_options)
152
+ add_default_name_and_id(html_options)
153
+ content_tag(
154
+ "select", add_blank_option(options_from_collection_for_select(collection, value_method, text_method, value), options[:include_blank]), html_options
155
+ )
156
+ end
157
+
158
+ def to_country_select_tag(priority_countries, options, html_options)
159
+ add_default_name_and_id(html_options)
160
+ content_tag("select", add_blank_option(country_options_for_select(value, priority_countries), options[:include_blank]), html_options)
161
+ end
162
+
163
+ private
164
+ def add_blank_option(option_tags, add_blank)
165
+ add_blank ? "<option></option>\n" + option_tags : option_tags
166
+ end
167
+ end
168
+ end
169
+ end