How to dynamically call routes helper in rails? How to dynamically call routes helper in rails? ruby ruby

How to dynamically call routes helper in rails?


try Rails.application.routes.url_helpers.send(...)

Edit:

As Larry Gebhardt mentioned the url_helpers module is no longer being cached.

Another workaround would be:

cached_helpers = Class.new do  include Rails.application.routes.url_helpers  include Rails.application.routes.mounted_helpersend.newcached_helpers.send(...)


My bad, as per @tadman suggested, I tried to use send(:new_work_path, args) again and it worked! Must have mistyped it before.

Before finding out that send works right away, I had found another solution which is also of interest:

new_polymorphic_path(Work, args)

Which seems to offer some syntactic sugar as well.


My two cents to the accepted answer.
Please always keep in mind that send is a risky command that you should avoid if possible, or at least having a white list of available options to be accepted by your send call. In case you don't want to use it, Rails have its own way to get paths dynamically with .url_for:

[5] pry(main)> include Rails.application.routes.url_helpers=> Object[6] pry(main)> url_for(controller: 'one_path/the_controller', action: 'valid_path')=> "http://localhost:3000/one_path/the_controller/valid_path"[7] pry(main)> url_for(controller: 'one_path/the_controller', action: 'some_h4cky_thing')ActionController::UrlGenerationError: No route matches {:action=>"some_h4cky_thing", :controller=>"one_path/the_controller"}

also .link_to has its own built-in option for this purpose:

<%= link_to "A link to #{option}", {controller: 'one_path/the_controller', action: option}, target: '_blank' %>