2017-04-14 67 views
0

我正在按照导轨指南进行高级约束Advanced Constraints。下面是代码:我应该在哪里为routes.rb定义一个约束?

class BlacklistConstraint 
    def initialize 
    @ips = Blacklist.retrieve_ips 
    end 

    def matches?(request) 
    @ips.include?(request.remote_ip) 
    end 
end 

Rails.application.routes.draw do 
    get '*path', to: 'blacklist#index', 
    constraints: BlacklistConstraint.new 
end 

的导游没有提到其中BlacklistConstraint应该被定义或者是否它遵循命名约定。我试图按照这个例子为自己使用,但我不断得到UninitialiezedConstantError: Can someone help me out? So far I;ve defined my constraint class in the 1 routes.rb file itself and in the lib`目录。两种方法都不起作用。

回答

1

此类的预期位置为库/约束条件

http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-constraints-label-Dynamic+request+matching

更新: 基础上有用的意见,我会尽量让这一个完整的答案。

根据您的约束类应该lib/constraints下放置的文档,但是由于lib目录并不急于通过轨装,你可以通过加入这行来config/application.rb

config.eager_load_paths << Rails.root.join('lib') 

启用它现在Rails会尝试加载lib/constraints/blacklist_constraint.rb文件,并希望它能够正确命名空间,所以在包装的模块类(这也使得它更清洁,因为你可能在未来更多的约束)

module Constraints 
    class BlacklistConstraint 
    def initialize 
     @ips = Blacklist.retrieve_ips 
    end 

    def matches?(request) 
     @ips.include?(request.remote_ip) 
    end 
    end 
end 

和参考Constraints::BlacklistConstraintroutes.rb

+0

感谢您的帮助,但由于某种原因,这并不适合我。我不得不在我的'application.rb'中需要文件路径。 –

+1

您必须打开自动加载/预先加载'lib'文件夹中的文件。 http://blog.bigbinary.com/2016/08/29/rails-5-disables-autoloading-after-booting-the-app-in-production.html – Iceman

相关问题