If you love messing with time in Ruby as much as I do you will appreciate this. This is a 12 hour time select. What separates this helper from time_select is that the hour select has 1am-12am and 1pm-12pm options. Therefore, the am/pm selection is removed. In addition, you have the ability to select minutes at different intervals easily. Enjoy
##################################### VIEW ##########################################
#12hr time with 15min intervals
<%= example_time_select(Time.now) %>
##################################### HELPER ########################################
def example_time_select(time)
return select_hour_with_twelve_hour_time(time, :field_name => 'hour',:prefix =>
'time') + ": " + select_minute_with_interval_of_fifteen(time,
:field_name => 'minute', :prefix => 'time')
end
def select_hour_with_twelve_hour_time(time, options = {})
val = time ? (time.kind_of?(Fixnum) ? time : time.hour) : ''
if options[:use_hidden]
hidden_html(options[:field_name] || 'hour', val, options)
else
hour_options = []
0.upto(23) do |hour|
ampm = hour <= 11 ? ' AM' : ' PM'
ampm_hour = hour == 12 ? 12 : (hour / 12 == 1 ? hour % 12 : hour)
hour_options << ((val == hour) ?
%(<option value="#{hour}"
selected="selected">#{ampm_hour}#{ampm}</option>\n) :
%(<option value="#{hour}">#{ampm_hour}#{ampm}</option>\n))
end
select_html(options[:field_name] || 'hour', hour_options, options)
end
end
def select_minute_with_interval_of_fifteen(time, options = {})
val = time ? (time.kind_of?(Fixnum) ? time : time.min) : ''
if options[:use_hidden]
hidden_html(options[:field_name] || 'minute', val, options)
else
minute_options = []
minute = 0
4.times do
if minute == 0
minute_options << ((val == minute) ?
%(<option value="#{minute}" selected="selected">0#{minute}</option>\n) :
%(<option value="#{minute}">0#{minute}</option>\n))
else
minute_options << ((val == minute) ?
%(<option value="#{minute}" selected="selected">#{minute}</option>\n) :
%(<option value="#{minute}">#{minute}</option>\n))
end
minute += 15
end
end
select_html(options[:field_name] || 'minute', minute_options, options)
end