Dex*_*Dex 2 routes constraints ruby-on-rails-3
我正在尝试这样做,以便我可以有这样的网址:
/events
/events/sunday # => The day is optional
Run Code Online (Sandbox Code Playgroud)
然而,即使我知道它被调用,它似乎也没有起作用.它位于我的路线文件的底部.
match '/:post(/:day_filter)' => 'posts#index', :as => post_day_filter, :constraints => DayFilter.new
class DayFilter
def initialize
@days = %w[all today tomorrow sunday monday tuesday wednesday thursday friday saturday]
end
def matches?(request)
return @days.include?(request.params[:day_filter]) if request.params[:day_filter]
true
end
end
Run Code Online (Sandbox Code Playgroud)
这是我的佣金路线输出:
post_day_filter /:post(/:day_filter)(.:format) {:controller=>"posts", :action=>"index"}
Run Code Online (Sandbox Code Playgroud)
我不确定问题是什么,具体来说,但以下是一种更加性能友好的方式来做同样的事情:
class ValidDayOfWeek
VALID_DAYS = %w[all today tomorrow sunday monday tuesday wednesday thursday friday saturday]
def self.matches?(request)
VALID_DAYS.include? request.params[:day_of_week]
end
end
get ':/post_type(/:day_of_week)' => 'posts#index', :constraints => ValidDayOfWeek
Run Code Online (Sandbox Code Playgroud)
最大的区别是这可以避免在每个请求上初始化一个新的ValidDayOfWeek对象.Rails指南给出了一个示例,您可能每次都需要一个新的对象(实时黑名单更新),但它会像您这样的情况产生误导.
此外,你都拿到你有点冗长matches?方法-不需要明确的收益或条件,如includes?将返回true或false原样.
| 归档时间: |
|
| 查看次数: |
2461 次 |
| 最近记录: |