Rails 3 Problem with Routes Constraint

本秂侑毒 提交于 2019-12-02 00:57:19

I'm not sure what the problem is, specifically, but the following is a much more performance-friendly way of doing the same thing:

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

The biggest difference is that this avoids initializing a new ValidDayOfWeek object on every request. The Rails guide gives an example where you might want a fresh object each time (real-time blacklist updating), but it's misleading for cases like yours.

Also, you were getting a bit verbose in your matches? method — no need for explicit returns or a conditional, as includes? will return either true or false as is.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!