How can I globally override a rails url helper?

前端 未结 4 2200
时光取名叫无心
时光取名叫无心 2020-12-06 12:30

I needed to add a simple change to foo_path, so I did this:

module ApplicationHelper
  # [...]

  def foo_path(foo, options = {})
    option         


        
4条回答
  •  情话喂你
    2020-12-06 13:10

    In Rails 3 and 4, route url helpers all resides in this module Rails.application.routes.url_helpers. So we can include a module to override methods inside it.

    module FooUrlHelper
      def foo_path(foo, options = {})
        options.merge!(bar: foo.some_attribute)
        super
      end
    end
    
    # Works at Rails 4.2.1
    Rails.application.routes.url_helpers.send(:include, FooUrlHelper)
    
    # For Rails 4.2.6, I thought the following worked, but there seems to be issues, don't have time to figure out a solution yet
    Rails.application.routes.named_routes.url_helpers_module.send(:include, FooUrlHelper)
    

    You can just place this inside initializers

    I tried this in console and controller and seems to work fine.

提交回复
热议问题