Module: Sinatra::DateForms::Helpers

Defined in:
lib/sinatra/support/dateforms.rb

Instance Method Summary collapse

Instance Method Details

#day_choices(max = 31) ⇒ Array

Returns an array of date pairs. Best used with HtmlHelpers#select_options.

An example output looks like:

- [1, 1]
- [2, 2]
- ...
- [31, 31]

Examples:

This is perfect for @select_options@.


<select name="date">
  <%= select_options day_choices %>

Returns:

  • (Array)

    the array of day, day pairs.



79
80
81
82
# File 'lib/sinatra/support/dateforms.rb', line 79

def day_choices(max=31)
  days = (1..max).to_a
  days.zip(days)
end

#month_choices(month_names = settings.default_month_names) ⇒ Array

Returns an array of pairs.

You may pass in @Date::ABBR_MONTHNAMES@ if you want the shortened month names.

Examples:

output


- ['January', 1]
- ['February', 2]
- ...
- ['December', 12]

Parameters:

  • month_names (Array) (defaults to: settings.default_month_names)

    (defaults to Date::MONTHNAMES) an array with the first element being nil, element 1 being January, etc.

Returns:

  • (Array)

    the array of month name, month pairs.



99
100
101
102
103
# File 'lib/sinatra/support/dateforms.rb', line 99

def month_choices(month_names = settings.default_month_names)
  month_names.map.
    with_index { |month, idx| [month, idx] }.
    tap        { |arr| arr.shift }
end

#year_choices(loffset = settings.default_year_loffset, uoffset = settings.default_year_uoffset) ⇒ Array

Returns an array of pairs.

Examples:

Output


- [2005, 2005]
- [2006, 2006]
- ...
- [2010, 2010]

year_choices # assuming it's now 2010
# => [[1950, 1950], ..., [2010, 2010]]

# we can pass in options
year_choices(0, 6) # like for credit card options
# => [[2010, 2010], ..., [2016, 2016]]

# also we can override settings at the app level
set :default_year_loffset, 0
set :default_year_uoffset, 6
year_choices
# => [[2010, 2010], ..., [2016, 2016]]

Parameters:

  • loffset (Fixnum) (defaults to: settings.default_year_loffset)

    (defaults to -60) The lower offset relative to the current year. If it’s 2010 now, passing in -5 here will start the year list at 2005 for example.

  • uoffset (Fixnum) (defaults to: settings.default_year_uoffset)

    (defaults to 0) The upper offset relative to the current year. If it’s 2010 now, passing in 5 or +5 here will end the year list at 2015 for example.

Returns:

  • (Array)

    the array of year, year pairs.



137
138
139
140
141
142
143
# File 'lib/sinatra/support/dateforms.rb', line 137

def year_choices(loffset = settings.default_year_loffset, uoffset = settings.default_year_uoffset)
  start  = loffset + Date.today.year
  finish = uoffset + Date.today.year
  
  enum   = start < finish ? start.upto(finish) : start.downto(finish)
  enum.map { |e| [e, e] }
end