route.rb 可以访问初始化程序的代码吗? [英] Can routes.rb Access Initializers' code?
问题描述
我一直在尝试编写一个路由表达式,如果 URL 后缀(即 www.example.com/suffix),它只会将请求转发到特定控制器(称为 sample_controller)对应于我的一个初始值设定项中的哈希键.否则,我希望 Rails 将请求路由到不同的控制器(例如,一个根引用).例如,给定一个散列 RELEVANT_HASH = {"a" =>;亚达",b"=>"bla"}
, www.example.com/a 会路由到 sample_controller,而 www.example.com/c 不会,而是加载 root 的路由.
I've been trying to write a routing expression that would only forward a request to a specific controller (call it sample_controller) if the URL suffix (namely, www.example.com/suffix) corresponds to a hash key in one of my initializers. Otherwise, I want Rails to route the request to a different controller (say, the one root refers to). For example, given a hash RELEVANT_HASH = {"a" => "yada", "b" => "bla"}
, www.example.com/a would route to sample_controller, while www.example.com/c would not, loading root's route instead.
我一直在努力做到这一点
I've been trying to do that by putting
match '/:page_name' => 'sample_controller#action', :as => :something, :constraints => lambda { |r| MyInitializer::RELEVANT_HASH.has_key?(r.params[:page_name]) }
在我的 routes.rb 文件中.但是,MyInitializer 在 routes.rb 的 do/end 块中不可用,因为它在 ActionDispatch::Routing::Mapper 的上下文中,导致 Rails 返回未初始化的常量 MyInitializer"错误.
in my routes.rb file. However, MyInitializer isn't available from inside routes.rb's do/end block since it is in the context of ActionDispatch::Routing::Mapper, causing Rails to return a 'uninitialized constant MyInitializer' error.
是否有一种解决方法可以使 MyInitializer 从 routes.rb 访问(例如,从 application.rb 引用它)?将我的代码放在 do/end 块之外会解决范围问题吗?或者有没有其他方法可以在不将 MyInitializer 暴露给 routes.rb 的情况下实现我的目标?
Is there a workaround that would make MyInitializer accessible from routes.rb (say, referring to it from application.rb)? Would placing my code outside the do/end block solve the scoping issue? Or is there an alternative way to achieve my goal without exposing MyInitializer to routes.rb?
推荐答案
有没有办法让 MyInitializer 可以从 routes.rb 访问?
是的,有.将此行添加到 routes.rb:
Yes, there is. Add this line to routes.rb:
require Rails.root.join('config', 'initializers', 'my_initializer.rb')
这篇关于route.rb 可以访问初始化程序的代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!