Rails initializer that runs *after* routes are loaded?

前端 未结 2 471
悲哀的现实
悲哀的现实 2020-12-20 11:40

I want to set a class attribute when my Rails app starts up. It requires inspecting some routes, so the routes need to be loaded before my custom code runs. I am having trou

相关标签:
2条回答
  • 2020-12-20 11:54

    If you're trying to run code in an initializer after the routes have loaded, you can try using the after: option:

    initializer "name_of_initializer", after: :add_routing_paths do |app|
      # do custom logic here
    end
    

    You can find initialization events here: http://guides.rubyonrails.org/configuring.html#initialization-events

    0 讨论(0)
  • 2020-12-20 11:56

    You can force the routes to be loaded before looking at Rails.application.routes with this:

    Rails.application.reload_routes!
    

    So try this in your config/application.rb:

    config.after_initialize do
      Rails.application.reload_routes!
      Rails.logger.info "#{Rails.application.routes.routes.map(&:path)}"
    end
    

    I've done similar things that needed to check the routes (for conflicts with /:slug routes) and I ended up putting the reload_routes! and the checking in a config.after_initialize like you're doing.

    0 讨论(0)
提交回复
热议问题