Can routes.rb Access Initializers' code?

坚强是说给别人听的谎言 提交于 2019-12-12 02:48:22

问题


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]) }

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.

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?


回答1:


Is there a workaround that would make MyInitializer accessible from routes.rb?

Yes, there is. Add this line to routes.rb:

require Rails.root.join('config', 'initializers', 'my_initializer.rb')


来源:https://stackoverflow.com/questions/18557403/can-routes-rb-access-initializers-code

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