问题
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