开发者

How can I apply http_referer constraint in rails 3?

I want to apply constraint in routes.rb on routes using http开发者_Go百科_referer how can I do that?

Thanks


You can do it one of two ways as far as I know.

Easier, but with less control:

#config/routes.rb
resources :waffles, :constraints => {:referer => 'http://wafflesarerad.com'}

More control:

#config/routes.rb
require 'referer_constraint'
constraints (RefererConstraint) do
  resources :waffles
end

#lib/referer_constraint.rb
class RefererConstraint
  def self.matches?(request)
    request.referer = 'http://wafflesarerad.com' ? true :false
  end
end

You can contstrain by any part of the request with the :constraints => hash in routes.rb. You can also right custom constraint classes that implement a class level method of matches?(request). That method should return true/false as to whether or not the constraint is met.


To improve upon Patrick's answer, I would suggest

  • Placing the constraint class in app/constraints/ instead of lib/, Rails will then pick it up automatically and you won't need to stick a require statement at the top of your routes file
  • Not using the ternary (?:) operator unnecessarily

I would do this instead:

#config/routes.rb
constraints (RefererConstraint) do
  resources :waffles
end

#app/constraints/referer_constraint.rb
class RefererConstraint
  def self.matches?(request)
    request.referer == 'http://wafflesarerad.com'
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜