Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/actionpack/lib/action_view/helpers/date_helper.rb

Revision 9031, 37.2 kB (checked in by david, 2 years ago)

Docfix (closes #11263) [Irfy]

  • Property svn:executable set to *
Line 
1 require "date"
2 require 'action_view/helpers/tag_helper'
3
4 module ActionView
5   module Helpers
6     # The Date Helper primarily creates select/option tags for different kinds of dates and date elements. All of the select-type methods
7     # share a number of common options that are as follows:
8     #
9     # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday" would give
10     #   birthday[month] instead of date[month] if passed to the select_month method.
11     # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
12     # * <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
13     #   method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead of "date[month]".
14     module DateHelper
15       include ActionView::Helpers::TagHelper
16       DEFAULT_PREFIX = 'date' unless const_defined?('DEFAULT_PREFIX')
17
18       # Reports the approximate distance in time between two Time or Date objects or integers as seconds.
19       # Set <tt>include_seconds</tt> to true if you want more detailed approximations when distance < 1 min, 29 secs
20       # Distances are reported based on the following table:
21       #
22       #   0 <-> 29 secs                                                             # => less than a minute
23       #   30 secs <-> 1 min, 29 secs                                                # => 1 minute
24       #   1 min, 30 secs <-> 44 mins, 29 secs                                       # => [2..44] minutes
25       #   44 mins, 30 secs <-> 89 mins, 29 secs                                     # => about 1 hour
26       #   89 mins, 29 secs <-> 23 hrs, 59 mins, 29 secs                             # => about [2..24] hours
27       #   23 hrs, 59 mins, 29 secs <-> 47 hrs, 59 mins, 29 secs                     # => 1 day
28       #   47 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs            # => [2..29] days
29       #   29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs   # => about 1 month
30       #   59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec                    # => [2..12] months
31       #   1 yr <-> 2 yrs minus 1 secs                                               # => about 1 year
32       #   2 yrs <-> max time or date                                                # => over [2..X] years
33       #
34       # With <tt>include_seconds</tt> = true and the difference < 1 minute 29 seconds:
35       #   0-4   secs      # => less than 5 seconds
36       #   5-9   secs      # => less than 10 seconds
37       #   10-19 secs      # => less than 20 seconds
38       #   20-39 secs      # => half a minute
39       #   40-59 secs      # => less than a minute
40       #   60-89 secs      # => 1 minute
41       #
42       # ==== Examples
43       #   from_time = Time.now
44       #   distance_of_time_in_words(from_time, from_time + 50.minutes)        # => about 1 hour
45       #   distance_of_time_in_words(from_time, 50.minutes.from_now)           # => about 1 hour
46       #   distance_of_time_in_words(from_time, from_time + 15.seconds)        # => less than a minute
47       #   distance_of_time_in_words(from_time, from_time + 15.seconds, true)  # => less than 20 seconds
48       #   distance_of_time_in_words(from_time, 3.years.from_now)              # => over 3 years
49       #   distance_of_time_in_words(from_time, from_time + 60.hours)          # => about 3 days
50       #   distance_of_time_in_words(from_time, from_time + 45.seconds, true)  # => less than a minute
51       #   distance_of_time_in_words(from_time, from_time - 45.seconds, true)  # => less than a minute
52       #   distance_of_time_in_words(from_time, 76.seconds.from_now)           # => 1 minute
53       #   distance_of_time_in_words(from_time, from_time + 1.year + 3.days)   # => about 1 year
54       #   distance_of_time_in_words(from_time, from_time + 4.years + 15.days + 30.minutes + 5.seconds) # => over 4 years
55       #
56       #   to_time = Time.now + 6.years + 19.days
57       #   distance_of_time_in_words(from_time, to_time, true)     # => over 6 years
58       #   distance_of_time_in_words(to_time, from_time, true)     # => over 6 years
59       #   distance_of_time_in_words(Time.now, Time.now)           # => less than a minute
60       #
61       def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
62         from_time = from_time.to_time if from_time.respond_to?(:to_time)
63         to_time = to_time.to_time if to_time.respond_to?(:to_time)
64         distance_in_minutes = (((to_time - from_time).abs)/60).round
65         distance_in_seconds = ((to_time - from_time).abs).round
66
67         case distance_in_minutes
68           when 0..1
69             return (distance_in_minutes == 0) ? 'less than a minute' : '1 minute' unless include_seconds
70             case distance_in_seconds
71               when 0..4   then 'less than 5 seconds'
72               when 5..9   then 'less than 10 seconds'
73               when 10..19 then 'less than 20 seconds'
74               when 20..39 then 'half a minute'
75               when 40..59 then 'less than a minute'
76               else             '1 minute'
77             end
78
79           when 2..44           then "#{distance_in_minutes} minutes"
80           when 45..89          then 'about 1 hour'
81           when 90..1439        then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
82           when 1440..2879      then '1 day'
83           when 2880..43199     then "#{(distance_in_minutes / 1440).round} days"
84           when 43200..86399    then 'about 1 month'
85           when 86400..525599   then "#{(distance_in_minutes / 43200).round} months"
86           when 525600..1051199 then 'about 1 year'
87           else                      "over #{(distance_in_minutes / 525600).round} years"
88         end
89       end
90
91       # Like distance_of_time_in_words, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
92       #
93       # ==== Examples
94       #   time_ago_in_words(3.minutes.from_now)       # => 3 minutes
95       #   time_ago_in_words(Time.now - 15.hours)      # => 15 hours
96       #   time_ago_in_words(Time.now)                 # => less than a minute
97       #
98       #   from_time = Time.now - 3.days - 14.minutes - 25.seconds     # => 3 days
99       def time_ago_in_words(from_time, include_seconds = false)
100         distance_of_time_in_words(from_time, Time.now, include_seconds)
101       end
102
103       alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
104
105       # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute (identified by
106       # +method+) on an object assigned to the template (identified by +object+). It's possible to tailor the selects through the +options+ hash,
107       # which accepts all the keys that each of the individual select builders do (like :use_month_numbers for select_month) as well as a range of
108       # discard options. The discard options are <tt>:discard_year</tt>, <tt>:discard_month</tt> and <tt>:discard_day</tt>. Set to true, they'll
109       # drop the respective select. Discarding the month select will also automatically discard the day select. It's also possible to explicitly
110       # set the order of the tags using the <tt>:order</tt> option with an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in
111       # the desired order. Symbols may be omitted and the respective select is not included.
112       #
113       # Pass the <tt>:default</tt> option to set the default date. Use a Time object or a Hash of :year, :month, :day, :hour, :minute, and :second.
114       #
115       # Passing :disabled => true as part of the +options+ will make elements inaccessible for change.
116       #
117       # If anything is passed in the html_options hash it will be applied to every select tag in the set.
118       #
119       # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
120       #
121       # ==== Examples
122       #   # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute
123       #   date_select("post", "written_on")
124       #
125       #   # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute,
126       #   # with the year in the year drop down box starting at 1995.
127       #   date_select("post", "written_on", :start_year => 1995)
128       #
129       #   # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute,
130       #   # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
131       #   # and without a day select box.
132       #   date_select("post", "written_on", :start_year => 1995, :use_month_numbers => true,
133       #                                     :discard_day => true, :include_blank => true)
134       #
135       #   # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute
136       #   # with the fields ordered as day, month, year rather than month, day, year.
137       #   date_select("post", "written_on", :order => [:day, :month, :year])
138       #
139       #   # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
140       #   # lacking a year field.
141       #   date_select("user", "birthday", :order => [:month, :day])
142       #
143       #   # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
144       #   # which is initially set to the date 3 days from the current date
145       #   date_select("post", "written_on", :default => 3.days.from_now)
146       #
147       #   # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
148       #   # that will have a default day of 20.
149       #   date_select("credit_card", "bill_due", :default => { :day => 20 })
150       #
151       # The selects are prepared for multi-parameter assignment to an Active Record object.
152       #
153       # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that all month
154       # choices are valid.
155       def date_select(object_name, method, options = {}, html_options = {})
156         InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_date_select_tag(options, html_options)
157       end
158
159       # Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified
160       # time-based attribute (identified by +method+) on an object assigned to the template (identified by +object+).
161       # You can include the seconds with <tt>:include_seconds</tt>.
162       #
163       # If anything is passed in the html_options hash it will be applied to every select tag in the set.
164       #
165       # ==== Examples
166       #   # Creates a time select tag that, when POSTed, will be stored in the post variable in the sunrise attribute
167       #   time_select("post", "sunrise")
168       #
169       #   # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
170       #   time_select("order", "submitted")
171       #
172       #   # Creates a time select tag that, when POSTed, will be stored in the mail variable in the sent_at attribute
173       #   time_select("mail", "sent_at")
174       #
175       #   # Creates a time select tag with a seconds field that, when POSTed, will be stored in the post variables in
176       #   # the sunrise attribute.
177       #   time_select("post", "start_time", :include_seconds => true)
178       #
179       #   # Creates a time select tag with a seconds field that, when POSTed, will be stored in the entry variables in
180       #   # the submission_time attribute.
181       #   time_select("entry", "submission_time", :include_seconds => true)
182       #
183       #   # You can set the :minute_step to 15 which will give you: 00, 15, 30 and 45.
184       #   time_select 'game', 'game_time', {:minute_step => 15}
185       #
186       # The selects are prepared for multi-parameter assignment to an Active Record object.
187       #
188       # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that all month
189       # choices are valid.
190       def time_select(object_name, method, options = {}, html_options = {})
191         InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_time_select_tag(options, html_options)
192       end
193
194       # Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based
195       # attribute (identified by +method+) on an object assigned to the template (identified by +object+). Examples:
196       #
197       # If anything is passed in the html_options hash it will be applied to every select tag in the set.
198       #
199       # ==== Examples
200       #   # Generates a datetime select that, when POSTed, will be stored in the post variable in the written_on attribute
201       #   datetime_select("post", "written_on")
202       #
203       #   # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
204       #   # post variable in the written_on attribute.
205       #   datetime_select("post", "written_on", :start_year => 1995)
206       #
207       #   # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will be stored in the
208       #   # trip variable in the departing attribute.
209       #   datetime_select("trip", "departing", :default => 3.days.from_now)
210       #
211       #   # Generates a datetime select that discards the type that, when POSTed, will be stored in the post variable as the written_on
212       #   # attribute.
213       #   datetime_select("post", "written_on", :discard_type => true)
214       #
215       # The selects are prepared for multi-parameter assignment to an Active Record object.
216       def datetime_select(object_name, method, options = {}, html_options = {})
217         InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_datetime_select_tag(options, html_options)
218       end
219
220       # Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the +datetime+.
221       # It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
222       # symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol, it
223       # will be appended onto the <tt>:order</tt> passed in. You can also add <tt>:date_separator</tt> and <tt>:time_separator</tt>
224       # keys to the +options+ to control visual display of the elements.
225       #
226       # If anything is passed in the html_options hash it will be applied to every select tag in the set.
227       #
228       # ==== Examples
229       #   my_date_time = Time.now + 4.days
230       #
231       #   # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
232       #   select_datetime(my_date_time)
233       #
234       #   # Generates a datetime select that defaults to today (no specified datetime)
235       #   select_datetime()
236       #
237       #   # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
238       #   # with the fields ordered year, month, day rather than month, day, year.
239       #   select_datetime(my_date_time, :order => [:year, :month, :day])
240       #
241       #   # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
242       #   # with a '/' between each date field.
243       #   select_datetime(my_date_time, :date_separator => '/')
244       #
245       #   # Generates a datetime select that discards the type of the field and defaults to the datetime in
246       #   # my_date_time (four days after today)
247       #   select_datetime(my_date_time, :discard_type => true)
248       #
249       #   # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
250       #   # prefixed with 'payday' rather than 'date'
251       #   select_datetime(my_date_time, :prefix => 'payday')
252       #
253       def select_datetime(datetime = Time.now, options = {}, html_options = {})
254         separator = options[:datetime_separator] || ''
255         select_date(datetime, options, html_options) + separator + select_time(datetime, options, html_options)
256        end
257
258       # Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
259       # It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
260       # symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol, it
261       # will be appended onto the <tt>:order</tt> passed in.
262       #
263       # If anything is passed in the html_options hash it will be applied to every select tag in the set.
264       #
265       # ==== Examples
266       #   my_date = Time.today + 6.days
267       #
268       #   # Generates a date select that defaults to the date in my_date (six days after today)
269       #   select_date(my_date)
270       #
271       #   # Generates a date select that defaults to today (no specified date)
272       #   select_date()
273       #
274       #   # Generates a date select that defaults to the date in my_date (six days after today)
275       #   # with the fields ordered year, month, day rather than month, day, year.
276       #   select_date(my_date, :order => [:year, :month, :day])
277       #
278       #   # Generates a date select that discards the type of the field and defaults to the date in
279       #   # my_date (six days after today)
280       #   select_datetime(my_date_time, :discard_type => true)
281       #
282       #   # Generates a date select that defaults to the datetime in my_date (six days after today)
283       #   # prefixed with 'payday' rather than 'date'
284       #   select_datetime(my_date_time, :prefix => 'payday')
285       #
286       def select_date(date = Date.today, options = {}, html_options = {})
287         options[:order] ||= []
288         [:year, :month, :day].each { |o| options[:order].push(o) unless options[:order].include?(o) }
289
290         select_date = ''
291         options[:order].each do |o|
292           select_date << self.send("select_#{o}", date, options, html_options)
293         end
294         select_date
295       end
296
297       # Returns a set of html select-tags (one for hour and minute)
298       # You can set <tt>:time_separator</tt> key to format the output, and
299       # the <tt>:include_seconds</tt> option to include an input for seconds.
300       #
301       # If anything is passed in the html_options hash it will be applied to every select tag in the set.
302       #
303       # ==== Examples
304       #   my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
305       #
306       #   # Generates a time select that defaults to the time in my_time
307       #   select_time(my_time)
308       #
309       #   # Generates a time select that defaults to the current time (no specified time)
310       #   select_time()
311       #
312       #   # Generates a time select that defaults to the time in my_time,
313       #   # which has fields separated by ':'
314       #   select_time(my_time, :time_separator => ':')
315       #
316       #   # Generates a time select that defaults to the time in my_time,
317       #   # that also includes an input for seconds
318       #   select_time(my_time, :include_seconds => true)
319       #
320       #   # Generates a time select that defaults to the time in my_time, that has fields
321       #   # separated by ':' and includes an input for seconds
322       #   select_time(my_time, :time_separator => ':', :include_seconds => true)
323       #
324       def select_time(datetime = Time.now, options = {}, html_options = {})
325         separator = options[:time_separator] || ''
326         select_hour(datetime, options, html_options) + separator + select_minute(datetime, options, html_options) + (options[:include_seconds] ? separator + select_second(datetime, options, html_options) : '')
327       end
328
329       # Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
330       # The <tt>second</tt> can also be substituted for a second number.
331       # Override the field name using the <tt>:field_name</tt> option, 'second' by default.
332       #
333       # ==== Examples
334       #   my_time = Time.now + 16.minutes
335       #
336       #   # Generates a select field for seconds that defaults to the seconds for the time in my_time
337       #   select_second(my_time)
338       #
339       #   # Generates a select field for seconds that defaults to the number given
340       #   select_second(33)
341       #
342       #   # Generates a select field for seconds that defaults to the seconds for the time in my_time
343       #   # that is named 'interval' rather than 'second'
344       #   select_second(my_time, :field_name => 'interval')
345       #
346       def select_second(datetime, options = {}, html_options = {})
347         val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.sec) : ''
348         if options[:use_hidden]
349           options[:include_seconds] ? hidden_html(options[:field_name] || 'second', val, options) : ''
350         else
351           second_options = []
352           0.upto(59) do |second|
353             second_options << ((val == second) ?
354               content_tag(:option, leading_zero_on_single_digits(second), :value => leading_zero_on_single_digits(second), :selected => "selected") :
355               content_tag(:option, leading_zero_on_single_digits(second), :value => leading_zero_on_single_digits(second))
356             )
357             second_options << "\n"
358           end
359           select_html(options[:field_name] || 'second', second_options.join, options, html_options)
360         end
361       end
362
363       # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
364       # Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute selected
365       # The <tt>minute</tt> can also be substituted for a minute number.
366       # Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
367       #
368       # ==== Examples
369       #   my_time = Time.now + 6.hours
370       #
371       #   # Generates a select field for minutes that defaults to the minutes for the time in my_time
372       #   select_minute(my_time)
373       #
374       #   # Generates a select field for minutes that defaults to the number given
375       #   select_minute(14)
376       #
377       #   # Generates a select field for minutes that defaults to the minutes for the time in my_time
378       #   # that is named 'stride' rather than 'second'
379       #   select_minute(my_time, :field_name => 'stride')
380       #
381       def select_minute(datetime, options = {}, html_options = {})
382         val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.min) : ''
383         if options[:use_hidden]
384           hidden_html(options[:field_name] || 'minute', val, options)
385         else
386           minute_options = []
387           0.step(59, options[:minute_step] || 1) do |minute|
388             minute_options << ((val == minute) ?
389               content_tag(:option, leading_zero_on_single_digits(minute), :value => leading_zero_on_single_digits(minute), :selected => "selected") :
390               content_tag(:option, leading_zero_on_single_digits(minute), :value => leading_zero_on_single_digits(minute))
391             )
392             minute_options << "\n"
393           end
394           select_html(options[:field_name] || 'minute', minute_options.join, options, html_options)
395          end
396       end
397
398       # Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
399       # The <tt>hour</tt> can also be substituted for a hour number.
400       # Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
401       #
402       # ==== Examples
403       #   my_time = Time.now + 6.hours
404       #
405       #   # Generates a select field for minutes that defaults to the minutes for the time in my_time
406       #   select_minute(my_time)
407       #
408       #   # Generates a select field for minutes that defaults to the number given
409       #   select_minute(14)
410       #
411       #   # Generates a select field for minutes that defaults to the minutes for the time in my_time
412       #   # that is named 'stride' rather than 'second'
413       #   select_minute(my_time, :field_name => 'stride')
414       #
415       def select_hour(datetime, options = {}, html_options = {})
416         val = datetime ? (datetime.kind_of?(Fixnum) ? datetime : datetime.hour) : ''
417         if options[:use_hidden]
418           hidden_html(options[:field_name] || 'hour', val, options)
419         else
420           hour_options = []
421           0.upto(23) do |hour|
422             hour_options << ((val == hour) ?
423               content_tag(:option, leading_zero_on_single_digits(hour), :value => leading_zero_on_single_digits(hour), :selected => "selected") :
424               content_tag(:option, leading_zero_on_single_digits(hour), :value => leading_zero_on_single_digits(hour))
425             )
426             hour_options << "\n"
427           end
428           select_html(options[:field_name] || 'hour', hour_options.join, options, html_options)
429         end
430       end
431
432       # Returns a select tag with options for each of the days 1 through 31 with the current day selected.
433       # The <tt>date</tt> can also be substituted for a hour number.
434       # Override the field name using the <tt>:field_name</tt> option, 'day' by default.
435       #
436       # ==== Examples
437       #   my_date = Time.today + 2.days
438       #
439       #   # Generates a select field for days that defaults to the day for the date in my_date
440       #   select_day(my_time)
441       #
442       #   # Generates a select field for days that defaults to the number given
443       #   select_day(5)
444       #
445       #   # Generates a select field for days that defaults to the day for the date in my_date
446       #   # that is named 'due' rather than 'day'
447       #   select_day(my_time, :field_name => 'due')
448       #
449       def select_day(date, options = {}, html_options = {})
450         val = date ? (date.kind_of?(Fixnum) ? date : date.day) : ''
451         if options[:use_hidden]
452           hidden_html(options[:field_name] || 'day', val, options)
453         else
454           day_options = []
455           1.upto(31) do |day|
456             day_options << ((val == day) ?
457               content_tag(:option, day, :value => day, :selected => "selected") :
458               content_tag(:option, day, :value => day)
459             )
460             day_options << "\n"
461           end
462           select_html(options[:field_name] || 'day', day_options.join, options, html_options)
463         end
464       end
465
466       # Returns a select tag with options for each of the months January through December with the current month selected.
467       # The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are used as values
468       # (what's submitted to the server). It's also possible to use month numbers for the presentation instead of names --
469       # set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you want both numbers and names,
470       # set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer to show month names as abbreviations,
471       # set the <tt>:use_short_month</tt> key in +options+ to true. If you want to use your own month names, set the
472       # <tt>:use_month_names</tt> key in +options+ to an array of 12 month names. Override the field name using the
473       # <tt>:field_name</tt> option, 'month' by default.
474       #
475       # ==== Examples
476       #   # Generates a select field for months that defaults to the current month that
477       #   # will use keys like "January", "March".
478       #   select_month(Date.today)
479       #
480       #   # Generates a select field for months that defaults to the current month that
481       #   # is named "start" rather than "month"
482       #   select_month(Date.today, :field_name => 'start')
483       #
484       #   # Generates a select field for months that defaults to the current month that
485       #   # will use keys like "1", "3".       
486       #   select_month(Date.today, :use_month_numbers => true)
487       #
488       #   # Generates a select field for months that defaults to the current month that
489       #   # will use keys like "1 - January", "3 - March".
490       #   select_month(Date.today, :add_month_numbers => true)
491       #
492       #   # Generates a select field for months that defaults to the current month that
493       #   # will use keys like "Jan", "Mar".
494       #   select_month(Date.today, :use_short_month => true)
495       #
496       #   # Generates a select field for months that defaults to the current month that
497       #   # will use keys like "Januar", "Marts."
498       #   select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...))
499       #
500       def select_month(date, options = {}, html_options = {})
501         val = date ? (date.kind_of?(Fixnum) ? date : date.month) : ''
502         if options[:use_hidden]
503           hidden_html(options[:field_name] || 'month', val, options)
504         else
505           month_options = []
506           month_names = options[:use_month_names] || (options[:use_short_month] ? Date::ABBR_MONTHNAMES : Date::MONTHNAMES)
507           month_names.unshift(nil) if month_names.size < 13
508           1.upto(12) do |month_number|
509             month_name = if options[:use_month_numbers]
510               month_number
511             elsif options[:add_month_numbers]
512               month_number.to_s + ' - ' + month_names[month_number]
513             else
514               month_names[month_number]
515             end
516
517             month_options << ((val == month_number) ?
518               content_tag(:option, month_name, :value => month_number, :selected => "selected") :
519               content_tag(:option, month_name, :value => month_number)
520             )
521             month_options << "\n"
522           end
523           select_html(options[:field_name] || 'month', month_options.join, options, html_options)
524         end
525       end
526
527       # 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
528       # can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the +options+. Both ascending and descending year
529       # lists are supported by making <tt>:start_year</tt> less than or greater than <tt>:end_year</tt>. The <tt>date</tt> can also be
530       # substituted for a year given as a number.  Override the field name using the <tt>:field_name</tt> option, 'year' by default.
531       #
532       # ==== Examples
533       #   # Generates a select field for years that defaults to the current year that
534       #   # has ascending year values
535       #   select_year(Date.today, :start_year => 1992, :end_year => 2007)
536       #
537       #   # Generates a select field for years that defaults to the current year that
538       #   # is named 'birth' rather than 'year'
539       #   select_year(Date.today, :field_name => 'birth')
540       #
541       #   # Generates a select field for years that defaults to the current year that
542       #   # has descending year values
543       #   select_year(Date.today, :start_year => 2005, :end_year => 1900)
544       #
545       #   # Generates a select field for years that defaults to the year 2006 that
546       #   # has ascending year values
547       #   select_year(2006, :start_year => 2000, :end_year => 2010)
548       #
549       def select_year(date, options = {}, html_options = {})
550         val = date ? (date.kind_of?(Fixnum) ? date : date.year) : ''
551         if options[:use_hidden]
552           hidden_html(options[:field_name] || 'year', val, options)
553         else
554           year_options = []
555           y = date ? (date.kind_of?(Fixnum) ? (y = (date == 0) ? Date.today.year : date) : date.year) : Date.today.year
556
557           start_year, end_year = (options[:start_year] || y-5), (options[:end_year] || y+5)
558           step_val = start_year < end_year ? 1 : -1
559           start_year.step(end_year, step_val) do |year|
560             year_options << ((val == year) ?
561               content_tag(:option, year, :value => year, :selected => "selected") :
562               content_tag(:option, year, :value => year)
563             )
564             year_options << "\n"
565           end
566           select_html(options[:field_name] || 'year', year_options.join, options, html_options)
567         end
568       end
569
570       private
571
572         def select_html(type, html_options, options, select_tag_options = {})
573           name_and_id_from_options(options, type)
574           select_options = {:id => options[:id], :name => options[:name]}
575           select_options.merge!(:disabled => 'disabled') if options[:disabled]
576           select_options.merge!(select_tag_options) unless select_tag_options.empty?
577           select_html = "\n"
578           select_html << content_tag(:option, '', :value => '') + "\n" if options[:include_blank]
579           select_html << html_options.to_s
580           content_tag(:select, select_html, select_options) + "\n"
581         end
582
583         def hidden_html(type, value, options)
584           name_and_id_from_options(options, type)
585           hidden_html = tag(:input, :type => "hidden", :id => options[:id], :name => options[:name], :value => value) + "\n"
586         end
587
588         def name_and_id_from_options(options, type)
589           options[:name] = (options[:prefix] || DEFAULT_PREFIX) + (options[:discard_type] ? '' : "[#{type}]")
590           options[:id] = options[:name].gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
591         end
592
593         def leading_zero_on_single_digits(number)
594           number > 9 ? number : "0#{number}"
595         end
596     end
597
598     class InstanceTag #:nodoc:
599       include DateHelper
600
601       def to_date_select_tag(options = {}, html_options = {})
602         date_or_time_select(options.merge(:discard_hour => true), html_options)
603       end
604
605       def to_time_select_tag(options = {}, html_options = {})
606         date_or_time_select(options.merge(:discard_year => true, :discard_month => true), html_options)
607       end
608
609       def to_datetime_select_tag(options = {}, html_options = {})
610         date_or_time_select(options, html_options)
611       end
612
613       private
614         def date_or_time_select(options, html_options = {})
615           defaults = { :discard_type => true }
616           options  = defaults.merge(options)
617           datetime = value(object)
618           datetime ||= default_time_from_options(options[:default]) unless options[:include_blank]
619
620           position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 }
621
622           order = (options[:order] ||= [:year, :month, :day])
623
624           # Discard explicit and implicit by not being included in the :order
625           discard = {}
626           discard[:year]   = true if options[:discard_year] or !order.include?(:year)
627           discard[:month]  = true if options[:discard_month] or !order.include?(:month)
628           discard[:day]    = true if options[:discard_day] or discard[:month] or !order.include?(:day)
629           discard[:hour]   = true if options[:discard_hour]
630           discard[:minute] = true if options[:discard_minute] or discard[:hour]
631           discard[:second] = true unless options[:include_seconds] && !discard[:minute]
632
633           # If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are valid
634           # (otherwise it could be 31 and february wouldn't be a valid date)
635           if datetime && discard[:day] && !discard[:month]
636             datetime = datetime.change(:day => 1)
637           end
638
639           # Maintain valid dates by including hidden fields for discarded elements
640           [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
641
642           # Ensure proper ordering of :hour, :minute and :second
643           [:hour, :minute, :second].each { |o| order.delete(o); order.push(o) }
644
645           date_or_time_select = ''
646           order.reverse.each do |param|
647             # Send hidden fields for discarded elements once output has started
648             # This ensures AR can reconstruct valid dates using ParseDate
649             next if discard[param] && date_or_time_select.empty?
650
651             date_or_time_select.insert(0, self.send("select_#{param}", datetime, options_with_prefix(position[param], options.merge(:use_hidden => discard[param])), html_options))
652             date_or_time_select.insert(0,
653               case param
654                 when :hour then (discard[:year] && discard[:day] ? "" : " &mdash; ")
655                 when :minute then " : "
656                 when :second then options[:include_seconds] ? " : " : ""
657                 else ""
658               end)
659
660           end
661
662           date_or_time_select
663         end
664
665         def options_with_prefix(position, options)
666           prefix = "#{@object_name}"
667           if options[:index]
668             prefix << "[#{options[:index]}]"
669           elsif @auto_index
670             prefix << "[#{@auto_index}]"
671           end
672           options.merge(:prefix => "#{prefix}[#{@method_name}(#{position}i)]")
673         end
674
675         def default_time_from_options(default)
676           case default
677             when nil
678               Time.now
679             when Date, Time
680               default
681             else
682               # Rename :minute and :second to :min and :sec
683               default[:min] ||= default[:minute]
684               default[:sec] ||= default[:second]
685
686               [:year, :month, :day, :hour, :min, :sec].each do |key|
687                 default[key] ||= Time.now.send(key)
688               end
689
690               Time.mktime(default[:year], default[:month], default[:day],
691                           default[:hour], default[:min],   default[:sec])
692             end
693         end
694     end
695
696     class FormBuilder
697       def date_select(method, options = {}, html_options = {})
698         @template.date_select(@object_name, method, options.merge(:object => @object))
699       end
700
701       def time_select(method, options = {}, html_options = {})
702         @template.time_select(@object_name, method, options.merge(:object => @object))
703       end
704
705       def datetime_select(method, options = {}, html_options = {})
706         @template.datetime_select(@object_name, method, options.merge(:object => @object))
707       end
708     end
709   end
710 end
Note: See TracBrowser for help on using the browser.