routes_lazy_routes icon indicating copy to clipboard operation
routes_lazy_routes copied to clipboard

The gem breaks usage of Rails URL helpers when used outside views and controllers

Open mechanicles opened this issue 2 years ago • 3 comments

Issue is mentioned here https://github.com/discourse/discourse/pull/14581.

I wanted to use this gem in our application after following this Twitter thread but found above issue so I couldn't use it. I hope that issue will get resolved soon.

mechanicles avatar Oct 13 '21 07:10 mechanicles

We ran in the same thing. One workaround I'm trying now is:

# config/initializer/console.rb
Rails.application.console do
  Rails.application.routes.url_helpers.instance_eval do
    def method_missing(m, *args, &block)
      if m.to_s.end_with?('_path', '_url')
        RoutesLazyRoutes.eager_load!
        return public_send(m, *args, &block)
      end

      super
    end

    def respond_to_missing?(m, include_private = false)
      m.to_s.end_with?('_path', '_url') || super
    end
  end
end

I've confirmed helpers in Rails.application.routes.url_helpers work after that, but the main unknown for me is how that will interact with reload!.

technicalpickles avatar Oct 20 '21 14:10 technicalpickles

To revisit my earlier comment... that workaround didn't work. Partially, it's because the Rails URL helpers aren't normally available in the console from the top level object. The underlying problem I was trying to fix was ActionMailers failing when they used URL helpers.

It came up for someone today, and I had a realization for a fix. In your `config/console

Rails.application.console do
  # Make sure that routes are available to Mailers when running from a console
  if defined?(RoutesLazyRoutes)
    ActiveSupport.on_load(:action_mailer) do
      before_action { RoutesLazyRoutes.eager_load! }
    end
  end

It seems this should be feasible in the railtie, so I can try a patch for this.

technicalpickles avatar Mar 09 '22 22:03 technicalpickles

For those using sidekiq, you can update your Sidekiq.configure_server block to be like:

# config/initializers/sidekiq.rb
Sidekiq.configure_server do |config|
  if defined?(RoutesLazyRoutes)
    Rails.application.config.after_initialize do
      RoutesLazyRoutes.eager_load!
    end
  end

technicalpickles avatar Mar 09 '22 22:03 technicalpickles