actionview 6.0.0

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 (113) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +271 -0
  3. data/MIT-LICENSE +21 -0
  4. data/README.rdoc +40 -0
  5. data/lib/action_view.rb +98 -0
  6. data/lib/action_view/base.rb +312 -0
  7. data/lib/action_view/buffers.rb +67 -0
  8. data/lib/action_view/cache_expiry.rb +54 -0
  9. data/lib/action_view/context.rb +32 -0
  10. data/lib/action_view/dependency_tracker.rb +175 -0
  11. data/lib/action_view/digestor.rb +126 -0
  12. data/lib/action_view/flows.rb +76 -0
  13. data/lib/action_view/gem_version.rb +17 -0
  14. data/lib/action_view/helpers.rb +66 -0
  15. data/lib/action_view/helpers/active_model_helper.rb +55 -0
  16. data/lib/action_view/helpers/asset_tag_helper.rb +488 -0
  17. data/lib/action_view/helpers/asset_url_helper.rb +470 -0
  18. data/lib/action_view/helpers/atom_feed_helper.rb +205 -0
  19. data/lib/action_view/helpers/cache_helper.rb +271 -0
  20. data/lib/action_view/helpers/capture_helper.rb +216 -0
  21. data/lib/action_view/helpers/controller_helper.rb +36 -0
  22. data/lib/action_view/helpers/csp_helper.rb +26 -0
  23. data/lib/action_view/helpers/csrf_helper.rb +35 -0
  24. data/lib/action_view/helpers/date_helper.rb +1200 -0
  25. data/lib/action_view/helpers/debug_helper.rb +36 -0
  26. data/lib/action_view/helpers/form_helper.rb +2569 -0
  27. data/lib/action_view/helpers/form_options_helper.rb +896 -0
  28. data/lib/action_view/helpers/form_tag_helper.rb +920 -0
  29. data/lib/action_view/helpers/javascript_helper.rb +95 -0
  30. data/lib/action_view/helpers/number_helper.rb +456 -0
  31. data/lib/action_view/helpers/output_safety_helper.rb +70 -0
  32. data/lib/action_view/helpers/rendering_helper.rb +101 -0
  33. data/lib/action_view/helpers/sanitize_helper.rb +171 -0
  34. data/lib/action_view/helpers/tag_helper.rb +314 -0
  35. data/lib/action_view/helpers/tags.rb +44 -0
  36. data/lib/action_view/helpers/tags/base.rb +196 -0
  37. data/lib/action_view/helpers/tags/check_box.rb +66 -0
  38. data/lib/action_view/helpers/tags/checkable.rb +18 -0
  39. data/lib/action_view/helpers/tags/collection_check_boxes.rb +36 -0
  40. data/lib/action_view/helpers/tags/collection_helpers.rb +119 -0
  41. data/lib/action_view/helpers/tags/collection_radio_buttons.rb +31 -0
  42. data/lib/action_view/helpers/tags/collection_select.rb +30 -0
  43. data/lib/action_view/helpers/tags/color_field.rb +27 -0
  44. data/lib/action_view/helpers/tags/date_field.rb +15 -0
  45. data/lib/action_view/helpers/tags/date_select.rb +74 -0
  46. data/lib/action_view/helpers/tags/datetime_field.rb +32 -0
  47. data/lib/action_view/helpers/tags/datetime_local_field.rb +21 -0
  48. data/lib/action_view/helpers/tags/datetime_select.rb +10 -0
  49. data/lib/action_view/helpers/tags/email_field.rb +10 -0
  50. data/lib/action_view/helpers/tags/file_field.rb +10 -0
  51. data/lib/action_view/helpers/tags/grouped_collection_select.rb +31 -0
  52. data/lib/action_view/helpers/tags/hidden_field.rb +10 -0
  53. data/lib/action_view/helpers/tags/label.rb +81 -0
  54. data/lib/action_view/helpers/tags/month_field.rb +15 -0
  55. data/lib/action_view/helpers/tags/number_field.rb +20 -0
  56. data/lib/action_view/helpers/tags/password_field.rb +14 -0
  57. data/lib/action_view/helpers/tags/placeholderable.rb +24 -0
  58. data/lib/action_view/helpers/tags/radio_button.rb +33 -0
  59. data/lib/action_view/helpers/tags/range_field.rb +10 -0
  60. data/lib/action_view/helpers/tags/search_field.rb +27 -0
  61. data/lib/action_view/helpers/tags/select.rb +43 -0
  62. data/lib/action_view/helpers/tags/tel_field.rb +10 -0
  63. data/lib/action_view/helpers/tags/text_area.rb +24 -0
  64. data/lib/action_view/helpers/tags/text_field.rb +34 -0
  65. data/lib/action_view/helpers/tags/time_field.rb +15 -0
  66. data/lib/action_view/helpers/tags/time_select.rb +10 -0
  67. data/lib/action_view/helpers/tags/time_zone_select.rb +22 -0
  68. data/lib/action_view/helpers/tags/translator.rb +39 -0
  69. data/lib/action_view/helpers/tags/url_field.rb +10 -0
  70. data/lib/action_view/helpers/tags/week_field.rb +15 -0
  71. data/lib/action_view/helpers/text_helper.rb +486 -0
  72. data/lib/action_view/helpers/translation_helper.rb +145 -0
  73. data/lib/action_view/helpers/url_helper.rb +676 -0
  74. data/lib/action_view/layouts.rb +433 -0
  75. data/lib/action_view/locale/en.yml +56 -0
  76. data/lib/action_view/log_subscriber.rb +96 -0
  77. data/lib/action_view/lookup_context.rb +316 -0
  78. data/lib/action_view/model_naming.rb +14 -0
  79. data/lib/action_view/path_set.rb +95 -0
  80. data/lib/action_view/railtie.rb +105 -0
  81. data/lib/action_view/record_identifier.rb +112 -0
  82. data/lib/action_view/renderer/abstract_renderer.rb +108 -0
  83. data/lib/action_view/renderer/partial_renderer.rb +563 -0
  84. data/lib/action_view/renderer/partial_renderer/collection_caching.rb +103 -0
  85. data/lib/action_view/renderer/renderer.rb +68 -0
  86. data/lib/action_view/renderer/streaming_template_renderer.rb +105 -0
  87. data/lib/action_view/renderer/template_renderer.rb +108 -0
  88. data/lib/action_view/rendering.rb +171 -0
  89. data/lib/action_view/routing_url_for.rb +146 -0
  90. data/lib/action_view/tasks/cache_digests.rake +25 -0
  91. data/lib/action_view/template.rb +393 -0
  92. data/lib/action_view/template/error.rb +161 -0
  93. data/lib/action_view/template/handlers.rb +92 -0
  94. data/lib/action_view/template/handlers/builder.rb +25 -0
  95. data/lib/action_view/template/handlers/erb.rb +84 -0
  96. data/lib/action_view/template/handlers/erb/erubi.rb +87 -0
  97. data/lib/action_view/template/handlers/html.rb +11 -0
  98. data/lib/action_view/template/handlers/raw.rb +11 -0
  99. data/lib/action_view/template/html.rb +43 -0
  100. data/lib/action_view/template/inline.rb +22 -0
  101. data/lib/action_view/template/raw_file.rb +28 -0
  102. data/lib/action_view/template/resolver.rb +394 -0
  103. data/lib/action_view/template/sources.rb +13 -0
  104. data/lib/action_view/template/sources/file.rb +17 -0
  105. data/lib/action_view/template/text.rb +35 -0
  106. data/lib/action_view/template/types.rb +57 -0
  107. data/lib/action_view/test_case.rb +300 -0
  108. data/lib/action_view/testing/resolvers.rb +67 -0
  109. data/lib/action_view/unbound_template.rb +32 -0
  110. data/lib/action_view/version.rb +10 -0
  111. data/lib/action_view/view_paths.rb +129 -0
  112. data/lib/assets/compiled/rails-ujs.js +746 -0
  113. metadata +260 -0
@@ -0,0 +1,216 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/string/output_safety"
4
+
5
+ module ActionView
6
+ # = Action View Capture Helper
7
+ module Helpers #:nodoc:
8
+ # CaptureHelper exposes methods to let you extract generated markup which
9
+ # can be used in other parts of a template or layout file.
10
+ #
11
+ # It provides a method to capture blocks into variables through capture and
12
+ # a way to capture a block of markup for use in a layout through {content_for}[rdoc-ref:ActionView::Helpers::CaptureHelper#content_for].
13
+ module CaptureHelper
14
+ # The capture method extracts part of a template as a String object.
15
+ # You can then use this object anywhere in your templates, layout, or helpers.
16
+ #
17
+ # The capture method can be used in ERB templates...
18
+ #
19
+ # <% @greeting = capture do %>
20
+ # Welcome to my shiny new web page! The date and time is
21
+ # <%= Time.now %>
22
+ # <% end %>
23
+ #
24
+ # ...and Builder (RXML) templates.
25
+ #
26
+ # @timestamp = capture do
27
+ # "The current timestamp is #{Time.now}."
28
+ # end
29
+ #
30
+ # You can then use that variable anywhere else. For example:
31
+ #
32
+ # <html>
33
+ # <head><title><%= @greeting %></title></head>
34
+ # <body>
35
+ # <b><%= @greeting %></b>
36
+ # </body>
37
+ # </html>
38
+ #
39
+ # The return of capture is the string generated by the block. For Example:
40
+ #
41
+ # @greeting # => "Welcome to my shiny new web page! The date and time is 2018-09-06 11:09:16 -0500"
42
+ #
43
+ def capture(*args)
44
+ value = nil
45
+ buffer = with_output_buffer { value = yield(*args) }
46
+ if (string = buffer.presence || value) && string.is_a?(String)
47
+ ERB::Util.html_escape string
48
+ end
49
+ end
50
+
51
+ # Calling <tt>content_for</tt> stores a block of markup in an identifier for later use.
52
+ # In order to access this stored content in other templates, helper modules
53
+ # or the layout, you would pass the identifier as an argument to <tt>content_for</tt>.
54
+ #
55
+ # Note: <tt>yield</tt> can still be used to retrieve the stored content, but calling
56
+ # <tt>yield</tt> doesn't work in helper modules, while <tt>content_for</tt> does.
57
+ #
58
+ # <% content_for :not_authorized do %>
59
+ # alert('You are not authorized to do that!')
60
+ # <% end %>
61
+ #
62
+ # You can then use <tt>content_for :not_authorized</tt> anywhere in your templates.
63
+ #
64
+ # <%= content_for :not_authorized if current_user.nil? %>
65
+ #
66
+ # This is equivalent to:
67
+ #
68
+ # <%= yield :not_authorized if current_user.nil? %>
69
+ #
70
+ # <tt>content_for</tt>, however, can also be used in helper modules.
71
+ #
72
+ # module StorageHelper
73
+ # def stored_content
74
+ # content_for(:storage) || "Your storage is empty"
75
+ # end
76
+ # end
77
+ #
78
+ # This helper works just like normal helpers.
79
+ #
80
+ # <%= stored_content %>
81
+ #
82
+ # You can also use the <tt>yield</tt> syntax alongside an existing call to
83
+ # <tt>yield</tt> in a layout. For example:
84
+ #
85
+ # <%# This is the layout %>
86
+ # <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
87
+ # <head>
88
+ # <title>My Website</title>
89
+ # <%= yield :script %>
90
+ # </head>
91
+ # <body>
92
+ # <%= yield %>
93
+ # </body>
94
+ # </html>
95
+ #
96
+ # And now, we'll create a view that has a <tt>content_for</tt> call that
97
+ # creates the <tt>script</tt> identifier.
98
+ #
99
+ # <%# This is our view %>
100
+ # Please login!
101
+ #
102
+ # <% content_for :script do %>
103
+ # <script>alert('You are not authorized to view this page!')</script>
104
+ # <% end %>
105
+ #
106
+ # Then, in another view, you could to do something like this:
107
+ #
108
+ # <%= link_to 'Logout', action: 'logout', remote: true %>
109
+ #
110
+ # <% content_for :script do %>
111
+ # <%= javascript_include_tag :defaults %>
112
+ # <% end %>
113
+ #
114
+ # That will place +script+ tags for your default set of JavaScript files on the page;
115
+ # this technique is useful if you'll only be using these scripts in a few views.
116
+ #
117
+ # Note that <tt>content_for</tt> concatenates (default) the blocks it is given for a particular
118
+ # identifier in order. For example:
119
+ #
120
+ # <% content_for :navigation do %>
121
+ # <li><%= link_to 'Home', action: 'index' %></li>
122
+ # <% end %>
123
+ #
124
+ # And in another place:
125
+ #
126
+ # <% content_for :navigation do %>
127
+ # <li><%= link_to 'Login', action: 'login' %></li>
128
+ # <% end %>
129
+ #
130
+ # Then, in another template or layout, this code would render both links in order:
131
+ #
132
+ # <ul><%= content_for :navigation %></ul>
133
+ #
134
+ # If the flush parameter is +true+ <tt>content_for</tt> replaces the blocks it is given. For example:
135
+ #
136
+ # <% content_for :navigation do %>
137
+ # <li><%= link_to 'Home', action: 'index' %></li>
138
+ # <% end %>
139
+ #
140
+ # <%# Add some other content, or use a different template: %>
141
+ #
142
+ # <% content_for :navigation, flush: true do %>
143
+ # <li><%= link_to 'Login', action: 'login' %></li>
144
+ # <% end %>
145
+ #
146
+ # Then, in another template or layout, this code would render only the last link:
147
+ #
148
+ # <ul><%= content_for :navigation %></ul>
149
+ #
150
+ # Lastly, simple content can be passed as a parameter:
151
+ #
152
+ # <% content_for :script, javascript_include_tag(:defaults) %>
153
+ #
154
+ # WARNING: <tt>content_for</tt> is ignored in caches. So you shouldn't use it for elements that will be fragment cached.
155
+ def content_for(name, content = nil, options = {}, &block)
156
+ if content || block_given?
157
+ if block_given?
158
+ options = content if content
159
+ content = capture(&block)
160
+ end
161
+ if content
162
+ options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content)
163
+ end
164
+ nil
165
+ else
166
+ @view_flow.get(name).presence
167
+ end
168
+ end
169
+
170
+ # The same as +content_for+ but when used with streaming flushes
171
+ # straight back to the layout. In other words, if you want to
172
+ # concatenate several times to the same buffer when rendering a given
173
+ # template, you should use +content_for+, if not, use +provide+ to tell
174
+ # the layout to stop looking for more contents.
175
+ def provide(name, content = nil, &block)
176
+ content = capture(&block) if block_given?
177
+ result = @view_flow.append!(name, content) if content
178
+ result unless content
179
+ end
180
+
181
+ # <tt>content_for?</tt> checks whether any content has been captured yet using <tt>content_for</tt>.
182
+ # Useful to render parts of your layout differently based on what is in your views.
183
+ #
184
+ # <%# This is the layout %>
185
+ # <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
186
+ # <head>
187
+ # <title>My Website</title>
188
+ # <%= yield :script %>
189
+ # </head>
190
+ # <body class="<%= content_for?(:right_col) ? 'two-column' : 'one-column' %>">
191
+ # <%= yield %>
192
+ # <%= yield :right_col %>
193
+ # </body>
194
+ # </html>
195
+ def content_for?(name)
196
+ @view_flow.get(name).present?
197
+ end
198
+
199
+ # Use an alternate output buffer for the duration of the block.
200
+ # Defaults to a new empty string.
201
+ def with_output_buffer(buf = nil) #:nodoc:
202
+ unless buf
203
+ buf = ActionView::OutputBuffer.new
204
+ if output_buffer && output_buffer.respond_to?(:encoding)
205
+ buf.force_encoding(output_buffer.encoding)
206
+ end
207
+ end
208
+ self.output_buffer, old_buffer = buf, output_buffer
209
+ yield
210
+ output_buffer
211
+ ensure
212
+ self.output_buffer = old_buffer
213
+ end
214
+ end
215
+ end
216
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/core_ext/module/attr_internal"
4
+
5
+ module ActionView
6
+ module Helpers #:nodoc:
7
+ # This module keeps all methods and behavior in ActionView
8
+ # that simply delegates to the controller.
9
+ module ControllerHelper #:nodoc:
10
+ attr_internal :controller, :request
11
+
12
+ CONTROLLER_DELEGATES = [:request_forgery_protection_token, :params,
13
+ :session, :cookies, :response, :headers, :flash, :action_name,
14
+ :controller_name, :controller_path]
15
+
16
+ delegate(*CONTROLLER_DELEGATES, to: :controller)
17
+
18
+ def assign_controller(controller)
19
+ if @_controller = controller
20
+ @_request = controller.request if controller.respond_to?(:request)
21
+ @_config = controller.config.inheritable_copy if controller.respond_to?(:config)
22
+ @_default_form_builder = controller.default_form_builder if controller.respond_to?(:default_form_builder)
23
+ end
24
+ end
25
+
26
+ def logger
27
+ controller.logger if controller.respond_to?(:logger)
28
+ end
29
+
30
+ def respond_to?(method_name, include_private = false)
31
+ return controller.respond_to?(method_name) if CONTROLLER_DELEGATES.include?(method_name.to_sym)
32
+ super
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActionView
4
+ # = Action View CSP Helper
5
+ module Helpers #:nodoc:
6
+ module CspHelper
7
+ # Returns a meta tag "csp-nonce" with the per-session nonce value
8
+ # for allowing inline <script> tags.
9
+ #
10
+ # <head>
11
+ # <%= csp_meta_tag %>
12
+ # </head>
13
+ #
14
+ # This is used by the Rails UJS helper to create dynamically
15
+ # loaded inline <script> elements.
16
+ #
17
+ def csp_meta_tag(**options)
18
+ if content_security_policy?
19
+ options[:name] = "csp-nonce"
20
+ options[:content] = content_security_policy_nonce
21
+ tag("meta", options)
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ActionView
4
+ # = Action View CSRF Helper
5
+ module Helpers #:nodoc:
6
+ module CsrfHelper
7
+ # Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site
8
+ # request forgery protection parameter and token, respectively.
9
+ #
10
+ # <head>
11
+ # <%= csrf_meta_tags %>
12
+ # </head>
13
+ #
14
+ # These are used to generate the dynamic forms that implement non-remote links with
15
+ # <tt>:method</tt>.
16
+ #
17
+ # You don't need to use these tags for regular forms as they generate their own hidden fields.
18
+ #
19
+ # For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the
20
+ # "X-CSRF-Token" HTTP header. If you are using rails-ujs this happens automatically.
21
+ #
22
+ def csrf_meta_tags
23
+ if defined?(protect_against_forgery?) && protect_against_forgery?
24
+ [
25
+ tag("meta", name: "csrf-param", content: request_forgery_protection_token),
26
+ tag("meta", name: "csrf-token", content: form_authenticity_token)
27
+ ].join("\n").html_safe
28
+ end
29
+ end
30
+
31
+ # For backwards compatibility.
32
+ alias csrf_meta_tag csrf_meta_tags
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,1200 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+ require "action_view/helpers/tag_helper"
5
+ require "active_support/core_ext/array/extract_options"
6
+ require "active_support/core_ext/date/conversions"
7
+ require "active_support/core_ext/hash/slice"
8
+ require "active_support/core_ext/object/acts_like"
9
+ require "active_support/core_ext/object/with_options"
10
+
11
+ module ActionView
12
+ module Helpers #:nodoc:
13
+ # = Action View Date Helpers
14
+ #
15
+ # The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time
16
+ # elements. All of the select-type methods share a number of common options that are as follows:
17
+ #
18
+ # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
19
+ # would give \birthday[month] instead of \date[month] if passed to the <tt>select_month</tt> method.
20
+ # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
21
+ # * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
22
+ # the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead
23
+ # of \date[month].
24
+ module DateHelper
25
+ MINUTES_IN_YEAR = 525600
26
+ MINUTES_IN_QUARTER_YEAR = 131400
27
+ MINUTES_IN_THREE_QUARTERS_YEAR = 394200
28
+
29
+ # Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds.
30
+ # Pass <tt>include_seconds: true</tt> if you want more detailed approximations when distance < 1 min, 29 secs.
31
+ # Distances are reported based on the following table:
32
+ #
33
+ # 0 <-> 29 secs # => less than a minute
34
+ # 30 secs <-> 1 min, 29 secs # => 1 minute
35
+ # 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
36
+ # 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
37
+ # 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
38
+ # 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day
39
+ # 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
40
+ # 29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month
41
+ # 44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months
42
+ # 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
43
+ # 1 yr <-> 1 yr, 3 months # => about 1 year
44
+ # 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year
45
+ # 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years
46
+ # 2 yrs <-> max time or date # => (same rules as 1 yr)
47
+ #
48
+ # With <tt>include_seconds: true</tt> and the difference < 1 minute 29 seconds:
49
+ # 0-4 secs # => less than 5 seconds
50
+ # 5-9 secs # => less than 10 seconds
51
+ # 10-19 secs # => less than 20 seconds
52
+ # 20-39 secs # => half a minute
53
+ # 40-59 secs # => less than a minute
54
+ # 60-89 secs # => 1 minute
55
+ #
56
+ # from_time = Time.now
57
+ # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
58
+ # distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
59
+ # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
60
+ # distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds
61
+ # distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years
62
+ # distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days
63
+ # distance_of_time_in_words(from_time, from_time + 45.seconds, include_seconds: true) # => less than a minute
64
+ # distance_of_time_in_words(from_time, from_time - 45.seconds, include_seconds: true) # => less than a minute
65
+ # distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute
66
+ # distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year
67
+ # distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years
68
+ # distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years
69
+ #
70
+ # to_time = Time.now + 6.years + 19.days
71
+ # distance_of_time_in_words(from_time, to_time, include_seconds: true) # => about 6 years
72
+ # distance_of_time_in_words(to_time, from_time, include_seconds: true) # => about 6 years
73
+ # distance_of_time_in_words(Time.now, Time.now) # => less than a minute
74
+ #
75
+ # With the <tt>scope</tt> option, you can define a custom scope for Rails
76
+ # to look up the translation.
77
+ #
78
+ # For example you can define the following in your locale (e.g. en.yml).
79
+ #
80
+ # datetime:
81
+ # distance_in_words:
82
+ # short:
83
+ # about_x_hours:
84
+ # one: 'an hour'
85
+ # other: '%{count} hours'
86
+ #
87
+ # See https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml
88
+ # for more examples.
89
+ #
90
+ # Which will then result in the following:
91
+ #
92
+ # from_time = Time.now
93
+ # distance_of_time_in_words(from_time, from_time + 50.minutes, scope: 'datetime.distance_in_words.short') # => "an hour"
94
+ # distance_of_time_in_words(from_time, from_time + 3.hours, scope: 'datetime.distance_in_words.short') # => "3 hours"
95
+ def distance_of_time_in_words(from_time, to_time = 0, options = {})
96
+ options = {
97
+ scope: :'datetime.distance_in_words'
98
+ }.merge!(options)
99
+
100
+ from_time = normalize_distance_of_time_argument_to_time(from_time)
101
+ to_time = normalize_distance_of_time_argument_to_time(to_time)
102
+ from_time, to_time = to_time, from_time if from_time > to_time
103
+ distance_in_minutes = ((to_time - from_time) / 60.0).round
104
+ distance_in_seconds = (to_time - from_time).round
105
+
106
+ I18n.with_options locale: options[:locale], scope: options[:scope] do |locale|
107
+ case distance_in_minutes
108
+ when 0..1
109
+ return distance_in_minutes == 0 ?
110
+ locale.t(:less_than_x_minutes, count: 1) :
111
+ locale.t(:x_minutes, count: distance_in_minutes) unless options[:include_seconds]
112
+
113
+ case distance_in_seconds
114
+ when 0..4 then locale.t :less_than_x_seconds, count: 5
115
+ when 5..9 then locale.t :less_than_x_seconds, count: 10
116
+ when 10..19 then locale.t :less_than_x_seconds, count: 20
117
+ when 20..39 then locale.t :half_a_minute
118
+ when 40..59 then locale.t :less_than_x_minutes, count: 1
119
+ else locale.t :x_minutes, count: 1
120
+ end
121
+
122
+ when 2...45 then locale.t :x_minutes, count: distance_in_minutes
123
+ when 45...90 then locale.t :about_x_hours, count: 1
124
+ # 90 mins up to 24 hours
125
+ when 90...1440 then locale.t :about_x_hours, count: (distance_in_minutes.to_f / 60.0).round
126
+ # 24 hours up to 42 hours
127
+ when 1440...2520 then locale.t :x_days, count: 1
128
+ # 42 hours up to 30 days
129
+ when 2520...43200 then locale.t :x_days, count: (distance_in_minutes.to_f / 1440.0).round
130
+ # 30 days up to 60 days
131
+ when 43200...86400 then locale.t :about_x_months, count: (distance_in_minutes.to_f / 43200.0).round
132
+ # 60 days up to 365 days
133
+ when 86400...525600 then locale.t :x_months, count: (distance_in_minutes.to_f / 43200.0).round
134
+ else
135
+ from_year = from_time.year
136
+ from_year += 1 if from_time.month >= 3
137
+ to_year = to_time.year
138
+ to_year -= 1 if to_time.month < 3
139
+ leap_years = (from_year > to_year) ? 0 : (from_year..to_year).count { |x| Date.leap?(x) }
140
+ minute_offset_for_leap_year = leap_years * 1440
141
+ # Discount the leap year days when calculating year distance.
142
+ # e.g. if there are 20 leap year days between 2 dates having the same day
143
+ # and month then the based on 365 days calculation
144
+ # the distance in years will come out to over 80 years when in written
145
+ # English it would read better as about 80 years.
146
+ minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year
147
+ remainder = (minutes_with_offset % MINUTES_IN_YEAR)
148
+ distance_in_years = (minutes_with_offset.div MINUTES_IN_YEAR)
149
+ if remainder < MINUTES_IN_QUARTER_YEAR
150
+ locale.t(:about_x_years, count: distance_in_years)
151
+ elsif remainder < MINUTES_IN_THREE_QUARTERS_YEAR
152
+ locale.t(:over_x_years, count: distance_in_years)
153
+ else
154
+ locale.t(:almost_x_years, count: distance_in_years + 1)
155
+ end
156
+ end
157
+ end
158
+ end
159
+
160
+ # Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
161
+ #
162
+ # time_ago_in_words(3.minutes.from_now) # => 3 minutes
163
+ # time_ago_in_words(3.minutes.ago) # => 3 minutes
164
+ # time_ago_in_words(Time.now - 15.hours) # => about 15 hours
165
+ # time_ago_in_words(Time.now) # => less than a minute
166
+ # time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds
167
+ #
168
+ # from_time = Time.now - 3.days - 14.minutes - 25.seconds
169
+ # time_ago_in_words(from_time) # => 3 days
170
+ #
171
+ # from_time = (3.days + 14.minutes + 25.seconds).ago
172
+ # time_ago_in_words(from_time) # => 3 days
173
+ #
174
+ # Note that you cannot pass a <tt>Numeric</tt> value to <tt>time_ago_in_words</tt>.
175
+ #
176
+ def time_ago_in_words(from_time, options = {})
177
+ distance_of_time_in_words(from_time, Time.now, options)
178
+ end
179
+
180
+ alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
181
+
182
+ # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based
183
+ # attribute (identified by +method+) on an object assigned to the template (identified by +object+).
184
+ #
185
+ # ==== Options
186
+ # * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
187
+ # "2" instead of "February").
188
+ # * <tt>:use_two_digit_numbers</tt> - Set to true if you want to display two digit month and day numbers (e.g.
189
+ # "02" instead of "February" and "08" instead of "8").
190
+ # * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full
191
+ # month names (e.g. "Feb" instead of "February").
192
+ # * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g.
193
+ # "2 - February" instead of "February").
194
+ # * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
195
+ # Note: You can also use Rails' i18n functionality for this.
196
+ # * <tt>:month_format_string</tt> - Set to a format string. The string gets passed keys +:number+ (integer)
197
+ # and +:name+ (string). A format string would be something like "%{name} (%<number>02d)" for example.
198
+ # See <tt>Kernel.sprintf</tt> for documentation on format sequences.
199
+ # * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
200
+ # * <tt>:time_separator</tt> - Specifies a string to separate the time fields. Default is "" (i.e. nothing).
201
+ # * <tt>:datetime_separator</tt>- Specifies a string to separate the date and time fields. Default is "" (i.e. nothing).
202
+ # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt> if
203
+ # you are creating new record. While editing existing record, <tt>:start_year</tt> defaults to
204
+ # the current selected year minus 5.
205
+ # * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Date.today.year + 5</tt> if
206
+ # you are creating new record. While editing existing record, <tt>:end_year</tt> defaults to
207
+ # the current selected year plus 5.
208
+ # * <tt>:year_format</tt> - Set format of years for year select. Lambda should be passed.
209
+ # * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
210
+ # as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
211
+ # first of the given month in order to not create invalid dates like 31 February.
212
+ # * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month
213
+ # as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
214
+ # * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
215
+ # as a hidden field instead of showing a select field.
216
+ # * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to
217
+ # customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
218
+ # select will not be shown (like when you set <tt>discard_xxx: true</tt>. Defaults to the order defined in
219
+ # the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
220
+ # * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
221
+ # dates.
222
+ # * <tt>:default</tt> - Set a default date if the affected date isn't set or is +nil+.
223
+ # * <tt>:selected</tt> - Set a date that overrides the actual value.
224
+ # * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled.
225
+ # * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings
226
+ # for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>.
227
+ # Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds)
228
+ # or the given prompt string.
229
+ # * <tt>:with_css_classes</tt> - Set to true or a hash of strings. Use true if you want to assign generic styles for
230
+ # select tags. This automatically set classes 'year', 'month', 'day', 'hour', 'minute' and 'second'. A hash of
231
+ # strings for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt>, <tt>:second</tt>
232
+ # will extend the select type with the given value. Use +html_options+ to modify every select tag in the set.
233
+ # * <tt>:use_hidden</tt> - Set to true if you only want to generate hidden input tags.
234
+ #
235
+ # If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
236
+ #
237
+ # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
238
+ #
239
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute.
240
+ # date_select("article", "written_on")
241
+ #
242
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
243
+ # # with the year in the year drop down box starting at 1995.
244
+ # date_select("article", "written_on", start_year: 1995)
245
+ #
246
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
247
+ # # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
248
+ # # and without a day select box.
249
+ # date_select("article", "written_on", start_year: 1995, use_month_numbers: true,
250
+ # discard_day: true, include_blank: true)
251
+ #
252
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute,
253
+ # # with two digit numbers used for months and days.
254
+ # date_select("article", "written_on", use_two_digit_numbers: true)
255
+ #
256
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
257
+ # # with the fields ordered as day, month, year rather than month, day, year.
258
+ # date_select("article", "written_on", order: [:day, :month, :year])
259
+ #
260
+ # # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
261
+ # # lacking a year field.
262
+ # date_select("user", "birthday", order: [:month, :day])
263
+ #
264
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
265
+ # # which is initially set to the date 3 days from the current date
266
+ # date_select("article", "written_on", default: 3.days.from_now)
267
+ #
268
+ # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute
269
+ # # which is set in the form with today's date, regardless of the value in the Active Record object.
270
+ # date_select("article", "written_on", selected: Date.today)
271
+ #
272
+ # # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
273
+ # # that will have a default day of 20.
274
+ # date_select("credit_card", "bill_due", default: { day: 20 })
275
+ #
276
+ # # Generates a date select with custom prompts.
277
+ # date_select("article", "written_on", prompt: { day: 'Select day', month: 'Select month', year: 'Select year' })
278
+ #
279
+ # # Generates a date select with custom year format.
280
+ # date_select("article", "written_on", year_format: ->(year) { "Heisei #{year - 1988}" })
281
+ #
282
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
283
+ #
284
+ # 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
285
+ # all month choices are valid.
286
+ def date_select(object_name, method, options = {}, html_options = {})
287
+ Tags::DateSelect.new(object_name, method, self, options, html_options).render
288
+ end
289
+
290
+ # Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a
291
+ # specified time-based attribute (identified by +method+) on an object assigned to the template (identified by
292
+ # +object+). You can include the seconds with <tt>:include_seconds</tt>. You can get hours in the AM/PM format
293
+ # with <tt>:ampm</tt> option.
294
+ #
295
+ # This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
296
+ # <tt>:ignore_date</tt> is set to +true+. If you set the <tt>:ignore_date</tt> to +true+, you must have a
297
+ # +date_select+ on the same method within the form otherwise an exception will be raised.
298
+ #
299
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
300
+ #
301
+ # # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute.
302
+ # time_select("article", "sunrise")
303
+ #
304
+ # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the article variables in
305
+ # # the sunrise attribute.
306
+ # time_select("article", "start_time", include_seconds: true)
307
+ #
308
+ # # You can set the <tt>:minute_step</tt> to 15 which will give you: 00, 15, 30, and 45.
309
+ # time_select 'game', 'game_time', { minute_step: 15 }
310
+ #
311
+ # # Creates a time select tag with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
312
+ # time_select("article", "written_on", prompt: { hour: 'Choose hour', minute: 'Choose minute', second: 'Choose seconds' })
313
+ # time_select("article", "written_on", prompt: { hour: true }) # generic prompt for hours
314
+ # time_select("article", "written_on", prompt: true) # generic prompts for all
315
+ #
316
+ # # You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM.
317
+ # time_select 'game', 'game_time', { ampm: true }
318
+ #
319
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
320
+ #
321
+ # 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
322
+ # all month choices are valid.
323
+ def time_select(object_name, method, options = {}, html_options = {})
324
+ Tags::TimeSelect.new(object_name, method, self, options, html_options).render
325
+ end
326
+
327
+ # Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a
328
+ # specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified
329
+ # by +object+).
330
+ #
331
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
332
+ #
333
+ # # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on
334
+ # # attribute.
335
+ # datetime_select("article", "written_on")
336
+ #
337
+ # # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
338
+ # # article variable in the written_on attribute.
339
+ # datetime_select("article", "written_on", start_year: 1995)
340
+ #
341
+ # # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will
342
+ # # be stored in the trip variable in the departing attribute.
343
+ # datetime_select("trip", "departing", default: 3.days.from_now)
344
+ #
345
+ # # Generate a datetime select with hours in the AM/PM format
346
+ # datetime_select("article", "written_on", ampm: true)
347
+ #
348
+ # # Generates a datetime select that discards the type that, when POSTed, will be stored in the article variable
349
+ # # as the written_on attribute.
350
+ # datetime_select("article", "written_on", discard_type: true)
351
+ #
352
+ # # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
353
+ # datetime_select("article", "written_on", prompt: { day: 'Choose day', month: 'Choose month', year: 'Choose year' })
354
+ # datetime_select("article", "written_on", prompt: { hour: true }) # generic prompt for hours
355
+ # datetime_select("article", "written_on", prompt: true) # generic prompts for all
356
+ #
357
+ # The selects are prepared for multi-parameter assignment to an Active Record object.
358
+ def datetime_select(object_name, method, options = {}, html_options = {})
359
+ Tags::DatetimeSelect.new(object_name, method, self, options, html_options).render
360
+ end
361
+
362
+ # Returns a set of HTML select-tags (one for year, month, day, hour, minute, and second) pre-selected with the
363
+ # +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with
364
+ # an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not
365
+ # supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add
366
+ # <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to
367
+ # control visual display of the elements.
368
+ #
369
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
370
+ #
371
+ # my_date_time = Time.now + 4.days
372
+ #
373
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today).
374
+ # select_datetime(my_date_time)
375
+ #
376
+ # # Generates a datetime select that defaults to today (no specified datetime)
377
+ # select_datetime()
378
+ #
379
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
380
+ # # with the fields ordered year, month, day rather than month, day, year.
381
+ # select_datetime(my_date_time, order: [:year, :month, :day])
382
+ #
383
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
384
+ # # with a '/' between each date field.
385
+ # select_datetime(my_date_time, date_separator: '/')
386
+ #
387
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
388
+ # # with a date fields separated by '/', time fields separated by '' and the date and time fields
389
+ # # separated by a comma (',').
390
+ # select_datetime(my_date_time, date_separator: '/', time_separator: '', datetime_separator: ',')
391
+ #
392
+ # # Generates a datetime select that discards the type of the field and defaults to the datetime in
393
+ # # my_date_time (four days after today)
394
+ # select_datetime(my_date_time, discard_type: true)
395
+ #
396
+ # # Generate a datetime field with hours in the AM/PM format
397
+ # select_datetime(my_date_time, ampm: true)
398
+ #
399
+ # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
400
+ # # prefixed with 'payday' rather than 'date'
401
+ # select_datetime(my_date_time, prefix: 'payday')
402
+ #
403
+ # # Generates a datetime select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
404
+ # select_datetime(my_date_time, prompt: { day: 'Choose day', month: 'Choose month', year: 'Choose year' })
405
+ # select_datetime(my_date_time, prompt: { hour: true }) # generic prompt for hours
406
+ # select_datetime(my_date_time, prompt: true) # generic prompts for all
407
+ def select_datetime(datetime = Time.current, options = {}, html_options = {})
408
+ DateTimeSelector.new(datetime, options, html_options).select_datetime
409
+ end
410
+
411
+ # Returns a set of HTML select-tags (one for year, month, and day) pre-selected with the +date+.
412
+ # It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
413
+ # symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order.
414
+ # If the array passed to the <tt>:order</tt> option does not contain all the three symbols, all tags will be hidden.
415
+ #
416
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
417
+ #
418
+ # my_date = Time.now + 6.days
419
+ #
420
+ # # Generates a date select that defaults to the date in my_date (six days after today).
421
+ # select_date(my_date)
422
+ #
423
+ # # Generates a date select that defaults to today (no specified date).
424
+ # select_date()
425
+ #
426
+ # # Generates a date select that defaults to the date in my_date (six days after today)
427
+ # # with the fields ordered year, month, day rather than month, day, year.
428
+ # select_date(my_date, order: [:year, :month, :day])
429
+ #
430
+ # # Generates a date select that discards the type of the field and defaults to the date in
431
+ # # my_date (six days after today).
432
+ # select_date(my_date, discard_type: true)
433
+ #
434
+ # # Generates a date select that defaults to the date in my_date,
435
+ # # which has fields separated by '/'.
436
+ # select_date(my_date, date_separator: '/')
437
+ #
438
+ # # Generates a date select that defaults to the datetime in my_date (six days after today)
439
+ # # prefixed with 'payday' rather than 'date'.
440
+ # select_date(my_date, prefix: 'payday')
441
+ #
442
+ # # Generates a date select with a custom prompt. Use <tt>prompt: true</tt> for generic prompts.
443
+ # select_date(my_date, prompt: { day: 'Choose day', month: 'Choose month', year: 'Choose year' })
444
+ # select_date(my_date, prompt: { hour: true }) # generic prompt for hours
445
+ # select_date(my_date, prompt: true) # generic prompts for all
446
+ def select_date(date = Date.current, options = {}, html_options = {})
447
+ DateTimeSelector.new(date, options, html_options).select_date
448
+ end
449
+
450
+ # Returns a set of HTML select-tags (one for hour and minute).
451
+ # You can set <tt>:time_separator</tt> key to format the output, and
452
+ # the <tt>:include_seconds</tt> option to include an input for seconds.
453
+ #
454
+ # If anything is passed in the html_options hash it will be applied to every select tag in the set.
455
+ #
456
+ # my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
457
+ #
458
+ # # Generates a time select that defaults to the time in my_time.
459
+ # select_time(my_time)
460
+ #
461
+ # # Generates a time select that defaults to the current time (no specified time).
462
+ # select_time()
463
+ #
464
+ # # Generates a time select that defaults to the time in my_time,
465
+ # # which has fields separated by ':'.
466
+ # select_time(my_time, time_separator: ':')
467
+ #
468
+ # # Generates a time select that defaults to the time in my_time,
469
+ # # that also includes an input for seconds.
470
+ # select_time(my_time, include_seconds: true)
471
+ #
472
+ # # Generates a time select that defaults to the time in my_time, that has fields
473
+ # # separated by ':' and includes an input for seconds.
474
+ # select_time(my_time, time_separator: ':', include_seconds: true)
475
+ #
476
+ # # Generate a time select field with hours in the AM/PM format
477
+ # select_time(my_time, ampm: true)
478
+ #
479
+ # # Generates a time select field with hours that range from 2 to 14
480
+ # select_time(my_time, start_hour: 2, end_hour: 14)
481
+ #
482
+ # # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
483
+ # select_time(my_time, prompt: { day: 'Choose day', month: 'Choose month', year: 'Choose year' })
484
+ # select_time(my_time, prompt: { hour: true }) # generic prompt for hours
485
+ # select_time(my_time, prompt: true) # generic prompts for all
486
+ def select_time(datetime = Time.current, options = {}, html_options = {})
487
+ DateTimeSelector.new(datetime, options, html_options).select_time
488
+ end
489
+
490
+ # Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
491
+ # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
492
+ # Override the field name using the <tt>:field_name</tt> option, 'second' by default.
493
+ #
494
+ # my_time = Time.now + 16.seconds
495
+ #
496
+ # # Generates a select field for seconds that defaults to the seconds for the time in my_time.
497
+ # select_second(my_time)
498
+ #
499
+ # # Generates a select field for seconds that defaults to the number given.
500
+ # select_second(33)
501
+ #
502
+ # # Generates a select field for seconds that defaults to the seconds for the time in my_time
503
+ # # that is named 'interval' rather than 'second'.
504
+ # select_second(my_time, field_name: 'interval')
505
+ #
506
+ # # Generates a select field for seconds with a custom prompt. Use <tt>prompt: true</tt> for a
507
+ # # generic prompt.
508
+ # select_second(14, prompt: 'Choose seconds')
509
+ def select_second(datetime, options = {}, html_options = {})
510
+ DateTimeSelector.new(datetime, options, html_options).select_second
511
+ end
512
+
513
+ # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
514
+ # Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute
515
+ # selected. The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
516
+ # Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
517
+ #
518
+ # my_time = Time.now + 10.minutes
519
+ #
520
+ # # Generates a select field for minutes that defaults to the minutes for the time in my_time.
521
+ # select_minute(my_time)
522
+ #
523
+ # # Generates a select field for minutes that defaults to the number given.
524
+ # select_minute(14)
525
+ #
526
+ # # Generates a select field for minutes that defaults to the minutes for the time in my_time
527
+ # # that is named 'moment' rather than 'minute'.
528
+ # select_minute(my_time, field_name: 'moment')
529
+ #
530
+ # # Generates a select field for minutes with a custom prompt. Use <tt>prompt: true</tt> for a
531
+ # # generic prompt.
532
+ # select_minute(14, prompt: 'Choose minutes')
533
+ def select_minute(datetime, options = {}, html_options = {})
534
+ DateTimeSelector.new(datetime, options, html_options).select_minute
535
+ end
536
+
537
+ # Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
538
+ # The <tt>datetime</tt> can be either a +Time+ or +DateTime+ object or an integer.
539
+ # Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
540
+ #
541
+ # my_time = Time.now + 6.hours
542
+ #
543
+ # # Generates a select field for hours that defaults to the hour for the time in my_time.
544
+ # select_hour(my_time)
545
+ #
546
+ # # Generates a select field for hours that defaults to the number given.
547
+ # select_hour(13)
548
+ #
549
+ # # Generates a select field for hours that defaults to the hour for the time in my_time
550
+ # # that is named 'stride' rather than 'hour'.
551
+ # select_hour(my_time, field_name: 'stride')
552
+ #
553
+ # # Generates a select field for hours with a custom prompt. Use <tt>prompt: true</tt> for a
554
+ # # generic prompt.
555
+ # select_hour(13, prompt: 'Choose hour')
556
+ #
557
+ # # Generate a select field for hours in the AM/PM format
558
+ # select_hour(my_time, ampm: true)
559
+ #
560
+ # # Generates a select field that includes options for hours from 2 to 14.
561
+ # select_hour(my_time, start_hour: 2, end_hour: 14)
562
+ def select_hour(datetime, options = {}, html_options = {})
563
+ DateTimeSelector.new(datetime, options, html_options).select_hour
564
+ end
565
+
566
+ # Returns a select tag with options for each of the days 1 through 31 with the current day selected.
567
+ # The <tt>date</tt> can also be substituted for a day number.
568
+ # If you want to display days with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
569
+ # Override the field name using the <tt>:field_name</tt> option, 'day' by default.
570
+ #
571
+ # my_date = Time.now + 2.days
572
+ #
573
+ # # Generates a select field for days that defaults to the day for the date in my_date.
574
+ # select_day(my_date)
575
+ #
576
+ # # Generates a select field for days that defaults to the number given.
577
+ # select_day(5)
578
+ #
579
+ # # Generates a select field for days that defaults to the number given, but displays it with two digits.
580
+ # select_day(5, use_two_digit_numbers: true)
581
+ #
582
+ # # Generates a select field for days that defaults to the day for the date in my_date
583
+ # # that is named 'due' rather than 'day'.
584
+ # select_day(my_date, field_name: 'due')
585
+ #
586
+ # # Generates a select field for days with a custom prompt. Use <tt>prompt: true</tt> for a
587
+ # # generic prompt.
588
+ # select_day(5, prompt: 'Choose day')
589
+ def select_day(date, options = {}, html_options = {})
590
+ DateTimeSelector.new(date, options, html_options).select_day
591
+ end
592
+
593
+ # Returns a select tag with options for each of the months January through December with the current month
594
+ # selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
595
+ # used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
596
+ # instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
597
+ # want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
598
+ # to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
599
+ # to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
600
+ # If you want to display months with a leading zero set the <tt>:use_two_digit_numbers</tt> key in +options+ to true.
601
+ # Override the field name using the <tt>:field_name</tt> option, 'month' by default.
602
+ #
603
+ # # Generates a select field for months that defaults to the current month that
604
+ # # will use keys like "January", "March".
605
+ # select_month(Date.today)
606
+ #
607
+ # # Generates a select field for months that defaults to the current month that
608
+ # # is named "start" rather than "month".
609
+ # select_month(Date.today, field_name: 'start')
610
+ #
611
+ # # Generates a select field for months that defaults to the current month that
612
+ # # will use keys like "1", "3".
613
+ # select_month(Date.today, use_month_numbers: true)
614
+ #
615
+ # # Generates a select field for months that defaults to the current month that
616
+ # # will use keys like "1 - January", "3 - March".
617
+ # select_month(Date.today, add_month_numbers: true)
618
+ #
619
+ # # Generates a select field for months that defaults to the current month that
620
+ # # will use keys like "Jan", "Mar".
621
+ # select_month(Date.today, use_short_month: true)
622
+ #
623
+ # # Generates a select field for months that defaults to the current month that
624
+ # # will use keys like "Januar", "Marts."
625
+ # select_month(Date.today, use_month_names: %w(Januar Februar Marts ...))
626
+ #
627
+ # # Generates a select field for months that defaults to the current month that
628
+ # # will use keys with two digit numbers like "01", "03".
629
+ # select_month(Date.today, use_two_digit_numbers: true)
630
+ #
631
+ # # Generates a select field for months with a custom prompt. Use <tt>prompt: true</tt> for a
632
+ # # generic prompt.
633
+ # select_month(14, prompt: 'Choose month')
634
+ def select_month(date, options = {}, html_options = {})
635
+ DateTimeSelector.new(date, options, html_options).select_month
636
+ end
637
+
638
+ # Returns a select tag with options for each of the five years on each side of the current, which is selected.
639
+ # The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the
640
+ # +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or
641
+ # greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number.
642
+ # Override the field name using the <tt>:field_name</tt> option, 'year' by default.
643
+ #
644
+ # # Generates a select field for years that defaults to the current year that
645
+ # # has ascending year values.
646
+ # select_year(Date.today, start_year: 1992, end_year: 2007)
647
+ #
648
+ # # Generates a select field for years that defaults to the current year that
649
+ # # is named 'birth' rather than 'year'.
650
+ # select_year(Date.today, field_name: 'birth')
651
+ #
652
+ # # Generates a select field for years that defaults to the current year that
653
+ # # has descending year values.
654
+ # select_year(Date.today, start_year: 2005, end_year: 1900)
655
+ #
656
+ # # Generates a select field for years that defaults to the year 2006 that
657
+ # # has ascending year values.
658
+ # select_year(2006, start_year: 2000, end_year: 2010)
659
+ #
660
+ # # Generates a select field for years with a custom prompt. Use <tt>prompt: true</tt> for a
661
+ # # generic prompt.
662
+ # select_year(14, prompt: 'Choose year')
663
+ def select_year(date, options = {}, html_options = {})
664
+ DateTimeSelector.new(date, options, html_options).select_year
665
+ end
666
+
667
+ # Returns an HTML time tag for the given date or time.
668
+ #
669
+ # time_tag Date.today # =>
670
+ # <time datetime="2010-11-04">November 04, 2010</time>
671
+ # time_tag Time.now # =>
672
+ # <time datetime="2010-11-04T17:55:45+01:00">November 04, 2010 17:55</time>
673
+ # time_tag Date.yesterday, 'Yesterday' # =>
674
+ # <time datetime="2010-11-03">Yesterday</time>
675
+ # time_tag Date.today, datetime: Date.today.strftime('%G-W%V') # =>
676
+ # <time datetime="2010-W44">November 04, 2010</time>
677
+ #
678
+ # <%= time_tag Time.now do %>
679
+ # <span>Right now</span>
680
+ # <% end %>
681
+ # # => <time datetime="2010-11-04T17:55:45+01:00"><span>Right now</span></time>
682
+ def time_tag(date_or_time, *args, &block)
683
+ options = args.extract_options!
684
+ format = options.delete(:format) || :long
685
+ content = args.first || I18n.l(date_or_time, format: format)
686
+
687
+ content_tag("time", content, options.reverse_merge(datetime: date_or_time.iso8601), &block)
688
+ end
689
+
690
+ private
691
+
692
+ def normalize_distance_of_time_argument_to_time(value)
693
+ if value.is_a?(Numeric)
694
+ Time.at(value)
695
+ elsif value.respond_to?(:to_time)
696
+ value.to_time
697
+ else
698
+ raise ArgumentError, "#{value.inspect} can't be converted to a Time value"
699
+ end
700
+ end
701
+ end
702
+
703
+ class DateTimeSelector #:nodoc:
704
+ include ActionView::Helpers::TagHelper
705
+
706
+ DEFAULT_PREFIX = "date"
707
+ POSITION = {
708
+ year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6
709
+ }.freeze
710
+
711
+ AMPM_TRANSLATION = Hash[
712
+ [[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"],
713
+ [4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"],
714
+ [8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"],
715
+ [12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"],
716
+ [16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"],
717
+ [20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]]
718
+ ].freeze
719
+
720
+ def initialize(datetime, options = {}, html_options = {})
721
+ @options = options.dup
722
+ @html_options = html_options.dup
723
+ @datetime = datetime
724
+ @options[:datetime_separator] ||= " &mdash; "
725
+ @options[:time_separator] ||= " : "
726
+ end
727
+
728
+ def select_datetime
729
+ order = date_order.dup
730
+ order -= [:hour, :minute, :second]
731
+ @options[:discard_year] ||= true unless order.include?(:year)
732
+ @options[:discard_month] ||= true unless order.include?(:month)
733
+ @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
734
+ @options[:discard_minute] ||= true if @options[:discard_hour]
735
+ @options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
736
+
737
+ set_day_if_discarded
738
+
739
+ if @options[:tag] && @options[:ignore_date]
740
+ select_time
741
+ else
742
+ [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
743
+ order += [:hour, :minute, :second] unless @options[:discard_hour]
744
+
745
+ build_selects_from_types(order)
746
+ end
747
+ end
748
+
749
+ def select_date
750
+ order = date_order.dup
751
+
752
+ @options[:discard_hour] = true
753
+ @options[:discard_minute] = true
754
+ @options[:discard_second] = true
755
+
756
+ @options[:discard_year] ||= true unless order.include?(:year)
757
+ @options[:discard_month] ||= true unless order.include?(:month)
758
+ @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
759
+
760
+ set_day_if_discarded
761
+
762
+ [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
763
+
764
+ build_selects_from_types(order)
765
+ end
766
+
767
+ def select_time
768
+ order = []
769
+
770
+ @options[:discard_month] = true
771
+ @options[:discard_year] = true
772
+ @options[:discard_day] = true
773
+ @options[:discard_second] ||= true unless @options[:include_seconds]
774
+
775
+ order += [:year, :month, :day] unless @options[:ignore_date]
776
+
777
+ order += [:hour, :minute]
778
+ order << :second if @options[:include_seconds]
779
+
780
+ build_selects_from_types(order)
781
+ end
782
+
783
+ def select_second
784
+ if @options[:use_hidden] || @options[:discard_second]
785
+ build_hidden(:second, sec) if @options[:include_seconds]
786
+ else
787
+ build_options_and_select(:second, sec)
788
+ end
789
+ end
790
+
791
+ def select_minute
792
+ if @options[:use_hidden] || @options[:discard_minute]
793
+ build_hidden(:minute, min)
794
+ else
795
+ build_options_and_select(:minute, min, step: @options[:minute_step])
796
+ end
797
+ end
798
+
799
+ def select_hour
800
+ if @options[:use_hidden] || @options[:discard_hour]
801
+ build_hidden(:hour, hour)
802
+ else
803
+ options = {}
804
+ options[:ampm] = @options[:ampm] || false
805
+ options[:start] = @options[:start_hour] || 0
806
+ options[:end] = @options[:end_hour] || 23
807
+ build_options_and_select(:hour, hour, options)
808
+ end
809
+ end
810
+
811
+ def select_day
812
+ if @options[:use_hidden] || @options[:discard_day]
813
+ build_hidden(:day, day || 1)
814
+ else
815
+ build_options_and_select(:day, day, start: 1, end: 31, leading_zeros: false, use_two_digit_numbers: @options[:use_two_digit_numbers])
816
+ end
817
+ end
818
+
819
+ def select_month
820
+ if @options[:use_hidden] || @options[:discard_month]
821
+ build_hidden(:month, month || 1)
822
+ else
823
+ month_options = []
824
+ 1.upto(12) do |month_number|
825
+ options = { value: month_number }
826
+ options[:selected] = "selected" if month == month_number
827
+ month_options << content_tag("option", month_name(month_number), options) + "\n"
828
+ end
829
+ build_select(:month, month_options.join)
830
+ end
831
+ end
832
+
833
+ def select_year
834
+ if !@datetime || @datetime == 0
835
+ val = "1"
836
+ middle_year = Date.today.year
837
+ else
838
+ val = middle_year = year
839
+ end
840
+
841
+ if @options[:use_hidden] || @options[:discard_year]
842
+ build_hidden(:year, val)
843
+ else
844
+ options = {}
845
+ options[:start] = @options[:start_year] || middle_year - 5
846
+ options[:end] = @options[:end_year] || middle_year + 5
847
+ options[:step] = options[:start] < options[:end] ? 1 : -1
848
+ options[:leading_zeros] = false
849
+ options[:max_years_allowed] = @options[:max_years_allowed] || 1000
850
+
851
+ if (options[:end] - options[:start]).abs > options[:max_years_allowed]
852
+ raise ArgumentError, "There are too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter."
853
+ end
854
+
855
+ build_select(:year, build_year_options(val, options))
856
+ end
857
+ end
858
+
859
+ private
860
+ %w( sec min hour day month year ).each do |method|
861
+ define_method(method) do
862
+ case @datetime
863
+ when Hash then @datetime[method.to_sym]
864
+ when Numeric then @datetime
865
+ when nil then nil
866
+ else @datetime.send(method)
867
+ end
868
+ end
869
+ end
870
+
871
+ # If the day is hidden, the day should be set to the 1st so all month and year choices are
872
+ # valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid.
873
+ def set_day_if_discarded
874
+ if @datetime && @options[:discard_day]
875
+ @datetime = @datetime.change(day: 1)
876
+ end
877
+ end
878
+
879
+ # Returns translated month names, but also ensures that a custom month
880
+ # name array has a leading +nil+ element.
881
+ def month_names
882
+ @month_names ||= begin
883
+ month_names = @options[:use_month_names] || translated_month_names
884
+ month_names.unshift(nil) if month_names.size < 13
885
+ month_names
886
+ end
887
+ end
888
+
889
+ # Returns translated month names.
890
+ # => [nil, "January", "February", "March",
891
+ # "April", "May", "June", "July",
892
+ # "August", "September", "October",
893
+ # "November", "December"]
894
+ #
895
+ # If <tt>:use_short_month</tt> option is set
896
+ # => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
897
+ # "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
898
+ def translated_month_names
899
+ key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
900
+ I18n.translate(key, locale: @options[:locale])
901
+ end
902
+
903
+ # Looks up month names by number (1-based):
904
+ #
905
+ # month_name(1) # => "January"
906
+ #
907
+ # If the <tt>:use_month_numbers</tt> option is passed:
908
+ #
909
+ # month_name(1) # => 1
910
+ #
911
+ # If the <tt>:use_two_month_numbers</tt> option is passed:
912
+ #
913
+ # month_name(1) # => '01'
914
+ #
915
+ # If the <tt>:add_month_numbers</tt> option is passed:
916
+ #
917
+ # month_name(1) # => "1 - January"
918
+ #
919
+ # If the <tt>:month_format_string</tt> option is passed:
920
+ #
921
+ # month_name(1) # => "January (01)"
922
+ #
923
+ # depending on the format string.
924
+ def month_name(number)
925
+ if @options[:use_month_numbers]
926
+ number
927
+ elsif @options[:use_two_digit_numbers]
928
+ "%02d" % number
929
+ elsif @options[:add_month_numbers]
930
+ "#{number} - #{month_names[number]}"
931
+ elsif format_string = @options[:month_format_string]
932
+ format_string % { number: number, name: month_names[number] }
933
+ else
934
+ month_names[number]
935
+ end
936
+ end
937
+
938
+ # Looks up year names by number.
939
+ #
940
+ # year_name(1998) # => 1998
941
+ #
942
+ # If the <tt>:year_format</tt> option is passed:
943
+ #
944
+ # year_name(1998) # => "Heisei 10"
945
+ def year_name(number)
946
+ if year_format_lambda = @options[:year_format]
947
+ year_format_lambda.call(number)
948
+ else
949
+ number
950
+ end
951
+ end
952
+
953
+ def date_order
954
+ @date_order ||= @options[:order] || translated_date_order
955
+ end
956
+
957
+ def translated_date_order
958
+ date_order = I18n.translate(:'date.order', locale: @options[:locale], default: [])
959
+ date_order = date_order.map(&:to_sym)
960
+
961
+ forbidden_elements = date_order - [:year, :month, :day]
962
+ if forbidden_elements.any?
963
+ raise StandardError,
964
+ "#{@options[:locale]}.date.order only accepts :year, :month and :day"
965
+ end
966
+
967
+ date_order
968
+ end
969
+
970
+ # Build full select tag from date type and options.
971
+ def build_options_and_select(type, selected, options = {})
972
+ build_select(type, build_options(selected, options))
973
+ end
974
+
975
+ # Build select option HTML from date value and options.
976
+ # build_options(15, start: 1, end: 31)
977
+ # => "<option value="1">1</option>
978
+ # <option value="2">2</option>
979
+ # <option value="3">3</option>..."
980
+ #
981
+ # If <tt>use_two_digit_numbers: true</tt> option is passed
982
+ # build_options(15, start: 1, end: 31, use_two_digit_numbers: true)
983
+ # => "<option value="1">01</option>
984
+ # <option value="2">02</option>
985
+ # <option value="3">03</option>..."
986
+ #
987
+ # If <tt>:step</tt> options is passed
988
+ # build_options(15, start: 1, end: 31, step: 2)
989
+ # => "<option value="1">1</option>
990
+ # <option value="3">3</option>
991
+ # <option value="5">5</option>..."
992
+ def build_options(selected, options = {})
993
+ options = {
994
+ leading_zeros: true, ampm: false, use_two_digit_numbers: false
995
+ }.merge!(options)
996
+
997
+ start = options.delete(:start) || 0
998
+ stop = options.delete(:end) || 59
999
+ step = options.delete(:step) || 1
1000
+ leading_zeros = options.delete(:leading_zeros)
1001
+
1002
+ select_options = []
1003
+ start.step(stop, step) do |i|
1004
+ value = leading_zeros ? sprintf("%02d", i) : i
1005
+ tag_options = { value: value }
1006
+ tag_options[:selected] = "selected" if selected == i
1007
+ text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value
1008
+ text = options[:ampm] ? AMPM_TRANSLATION[i] : text
1009
+ select_options << content_tag("option", text, tag_options)
1010
+ end
1011
+
1012
+ (select_options.join("\n") + "\n").html_safe
1013
+ end
1014
+
1015
+ # Build select option HTML for year.
1016
+ # If <tt>year_format</tt> option is not passed
1017
+ # build_year_options(1998, start: 1998, end: 2000)
1018
+ # => "<option value="1998" selected="selected">1998</option>
1019
+ # <option value="1999">1999</option>
1020
+ # <option value="2000">2000</option>"
1021
+ #
1022
+ # If <tt>year_format</tt> option is passed
1023
+ # build_year_options(1998, start: 1998, end: 2000, year_format: ->year { "Heisei #{ year - 1988 }" })
1024
+ # => "<option value="1998" selected="selected">Heisei 10</option>
1025
+ # <option value="1999">Heisei 11</option>
1026
+ # <option value="2000">Heisei 12</option>"
1027
+ def build_year_options(selected, options = {})
1028
+ start = options.delete(:start)
1029
+ stop = options.delete(:end)
1030
+ step = options.delete(:step)
1031
+
1032
+ select_options = []
1033
+ start.step(stop, step) do |value|
1034
+ tag_options = { value: value }
1035
+ tag_options[:selected] = "selected" if selected == value
1036
+ text = year_name(value)
1037
+ select_options << content_tag("option", text, tag_options)
1038
+ end
1039
+
1040
+ (select_options.join("\n") + "\n").html_safe
1041
+ end
1042
+
1043
+ # Builds select tag from date type and HTML select options.
1044
+ # build_select(:month, "<option value="1">January</option>...")
1045
+ # => "<select id="post_written_on_2i" name="post[written_on(2i)]">
1046
+ # <option value="1">January</option>...
1047
+ # </select>"
1048
+ def build_select(type, select_options_as_html)
1049
+ select_options = {
1050
+ id: input_id_from_type(type),
1051
+ name: input_name_from_type(type)
1052
+ }.merge!(@html_options)
1053
+ select_options[:disabled] = "disabled" if @options[:disabled]
1054
+ select_options[:class] = css_class_attribute(type, select_options[:class], @options[:with_css_classes]) if @options[:with_css_classes]
1055
+
1056
+ select_html = +"\n"
1057
+ select_html << content_tag("option", "", value: "") + "\n" if @options[:include_blank]
1058
+ select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
1059
+ select_html << select_options_as_html
1060
+
1061
+ (content_tag("select", select_html.html_safe, select_options) + "\n").html_safe
1062
+ end
1063
+
1064
+ # Builds the css class value for the select element
1065
+ # css_class_attribute(:year, 'date optional', { year: 'my-year' })
1066
+ # => "date optional my-year"
1067
+ def css_class_attribute(type, html_options_class, options) # :nodoc:
1068
+ css_class = \
1069
+ case options
1070
+ when Hash
1071
+ options[type.to_sym]
1072
+ else
1073
+ type
1074
+ end
1075
+
1076
+ [html_options_class, css_class].compact.join(" ")
1077
+ end
1078
+
1079
+ # Builds a prompt option tag with supplied options or from default options.
1080
+ # prompt_option_tag(:month, prompt: 'Select month')
1081
+ # => "<option value="">Select month</option>"
1082
+ def prompt_option_tag(type, options)
1083
+ prompt = \
1084
+ case options
1085
+ when Hash
1086
+ default_options = { year: false, month: false, day: false, hour: false, minute: false, second: false }
1087
+ default_options.merge!(options)[type.to_sym]
1088
+ when String
1089
+ options
1090
+ else
1091
+ I18n.translate(:"datetime.prompts.#{type}", locale: @options[:locale])
1092
+ end
1093
+
1094
+ prompt ? content_tag("option", prompt, value: "") : ""
1095
+ end
1096
+
1097
+ # Builds hidden input tag for date part and value.
1098
+ # build_hidden(:year, 2008)
1099
+ # => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
1100
+ def build_hidden(type, value)
1101
+ select_options = {
1102
+ type: "hidden",
1103
+ id: input_id_from_type(type),
1104
+ name: input_name_from_type(type),
1105
+ value: value
1106
+ }.merge!(@html_options.slice(:disabled))
1107
+ select_options[:disabled] = "disabled" if @options[:disabled]
1108
+
1109
+ tag(:input, select_options) + "\n".html_safe
1110
+ end
1111
+
1112
+ # Returns the name attribute for the input tag.
1113
+ # => post[written_on(1i)]
1114
+ def input_name_from_type(type)
1115
+ prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
1116
+ prefix += "[#{@options[:index]}]" if @options.has_key?(:index)
1117
+
1118
+ field_name = @options[:field_name] || type.to_s
1119
+ if @options[:include_position]
1120
+ field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)"
1121
+ end
1122
+
1123
+ @options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
1124
+ end
1125
+
1126
+ # Returns the id attribute for the input tag.
1127
+ # => "post_written_on_1i"
1128
+ def input_id_from_type(type)
1129
+ id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, "_").gsub(/[\]\)]/, "")
1130
+ id = @options[:namespace] + "_" + id if @options[:namespace]
1131
+
1132
+ id
1133
+ end
1134
+
1135
+ # Given an ordering of datetime components, create the selection HTML
1136
+ # and join them with their appropriate separators.
1137
+ def build_selects_from_types(order)
1138
+ select = +""
1139
+ first_visible = order.find { |type| !@options[:"discard_#{type}"] }
1140
+ order.reverse_each do |type|
1141
+ separator = separator(type) unless type == first_visible # don't add before first visible field
1142
+ select.insert(0, separator.to_s + send("select_#{type}").to_s)
1143
+ end
1144
+ select.html_safe
1145
+ end
1146
+
1147
+ # Returns the separator for a given datetime component.
1148
+ def separator(type)
1149
+ return "" if @options[:use_hidden]
1150
+
1151
+ case type
1152
+ when :year, :month, :day
1153
+ @options[:"discard_#{type}"] ? "" : @options[:date_separator]
1154
+ when :hour
1155
+ (@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator]
1156
+ when :minute, :second
1157
+ @options[:"discard_#{type}"] ? "" : @options[:time_separator]
1158
+ end
1159
+ end
1160
+ end
1161
+
1162
+ class FormBuilder
1163
+ # Wraps ActionView::Helpers::DateHelper#date_select for form builders:
1164
+ #
1165
+ # <%= form_for @person do |f| %>
1166
+ # <%= f.date_select :birth_date %>
1167
+ # <%= f.submit %>
1168
+ # <% end %>
1169
+ #
1170
+ # Please refer to the documentation of the base helper for details.
1171
+ def date_select(method, options = {}, html_options = {})
1172
+ @template.date_select(@object_name, method, objectify_options(options), html_options)
1173
+ end
1174
+
1175
+ # Wraps ActionView::Helpers::DateHelper#time_select for form builders:
1176
+ #
1177
+ # <%= form_for @race do |f| %>
1178
+ # <%= f.time_select :average_lap %>
1179
+ # <%= f.submit %>
1180
+ # <% end %>
1181
+ #
1182
+ # Please refer to the documentation of the base helper for details.
1183
+ def time_select(method, options = {}, html_options = {})
1184
+ @template.time_select(@object_name, method, objectify_options(options), html_options)
1185
+ end
1186
+
1187
+ # Wraps ActionView::Helpers::DateHelper#datetime_select for form builders:
1188
+ #
1189
+ # <%= form_for @person do |f| %>
1190
+ # <%= f.datetime_select :last_request_at %>
1191
+ # <%= f.submit %>
1192
+ # <% end %>
1193
+ #
1194
+ # Please refer to the documentation of the base helper for details.
1195
+ def datetime_select(method, options = {}, html_options = {})
1196
+ @template.datetime_select(@object_name, method, objectify_options(options), html_options)
1197
+ end
1198
+ end
1199
+ end
1200
+ end