Routes with dates

So, I have a weekly view of the calendar, and I have a route configured to receive /: year /: month /: day for the start date.

  match "events/(:year/:month/:day)" => "events#index", 
      :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ },
      :as => "events_date"

I have two questions regarding the use of this route. First, when analyzing the parameters, this is what I do:

unless params[:year].nil? || params[:month].nil? || params[:day].nil?
  start_date = Date.new(params[:year].to_i, params[:month].to_i, params[:day].to_i)
end
start_date = start_date.nil? ? Date.today : start_date

It strikes me as rather verbose and ugly. Is there a better way?

And when you make a link to another week on the calendar (for the weekly swap week), I need to do something like

#assume an date object with the desired start date
link_to events_date_path(date.strftime('%Y'), date.strftime('%m'), date.strftime('%d'))

Which also seems pretty verbose and ugly. What is the best way to work with dates in routes?

+5
source share
1 answer

, . , . , :

match "events/(:date)" => "events#index", 
      :constraints => { :date => /\d{4}-\d{2}-\d{2}/ },
      :as => "events_date"

, - :

unless params[:date]
  start_date = params[:date].strftime("%Y-%m-%d').to_date # assuming you want a Date
end

" " - , :

start_date = Date.today unless defined? start_date

:

start_date = defined?(params[:date]) ? params[:date].strftime("%Y-%m-%d').to_date : Date.today
+8

All Articles