Search code examples
ruby-on-railsruby-on-rails-4initializer

Can't use url_helpers link_to in initializer


So I am extending String in an initializer that requires a model_path function to be used:

class String
  def foo(bar)
    ...
    link_to(baz, baz_path(baz))
  end
end

So to get it to work I add

include Rails.application.routes.url_helpers

Problem is now I can't even view the website because there are weird problems with using url_for elsewhere:

wrong number of arguments (3 for 0..1)

  </script>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
--<%= mathjax_tag %>------- this line is highlighted as the problem --
  <%= csrf_meta_tags %>
</head>
<body>

If I remove that include, my application views get rendered successfully again. But remove that include, and my extension to the String class does not work anymore.

How can I keep the functionality of my function (I'm ok with moving it elsewhere if need be, so long as it's accessible to all of my models) and also keep the views rendered?


Solution

  • Including url_helpers into String just to use something_path method is shooting sparrows with a cannon. Rails is already a big mess of monkeypatching, no need to add more (you're almost guaranteed to break something).

    Be less impactful and use url helpers without mixing them in:

    Rails.application.routes.url_helpers.user_path
    

    I would also advise not to extend String at all. An excusable exception would be if you wanted to add new string-related functionality (something like upcase if it didn't exist). It seems to be not the case, so don't do it.