日期 、路由辅助方法

#31 Formatting Time

方法一:
Task.first.due_at.to_s 	        =>2009-02-19 00:00:00 UTC
Task.first.due_at.to_s          =>(:long) 	February 19, 2009 00:00
Task.first.due_at.to_s(:short) 	=>19 Feb 00:00
Task.first.due_at.to_s(:long)
Task.first.due_at.to_s(:db) 	  =>2009-02-19 00:00:00

方法二、
<%= task.due_at.strftime("due on %B %d at %I:%M %p") %></li>

方法三、
environment.rb
Time::DATE_FORMATS[:due_date] = "due on %B %d at %I:%M %p"
<%= task.due_at.to_s(:due_date) %></li>


#32 Time in Text Field

<% form_for @task do |form| %>
    ...
    <%= form.label :due_at_string, "Due at" %>
    <%= form.text_field :due_at_string %>
    ...  
<% end %>

class Task < ActiveRecord::Base  
  def validate
    errors.add(:due_at, "is invalid") if @due_at_invalid
  end   
  
  def due_at_string
    due_at.to_s(:db)
  end

  def due_at_string=(due_at_str)
    self.due_at = Time.parse(due_at_str)
  rescue ArgumentError
    @due_at_invalid = true
  end  
end

扩展:chronic http://chronic.rubyforge.org/
$ sudo gem install chronic  
Chronic.parse('tomorrow')    #=> Mon Aug 28 12:00:00 PDT 2006


#35 Custom REST Actions
#routes.rb

map.resources :tasks, :collection => { :completed => :get }, :member => { :complete => :put }

t#asks/index.rhtml

<%= link_to "Mark as complete", complete_task_path(task), :method => :put %>
...
<%= link_to "Completed Tasks", completed_tasks_path %>

你可能感兴趣的:(Ruby)