2

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?

wrongusername
  • 18,564
  • 40
  • 130
  • 214

2 Answers2

2

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.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
-2

To add on the previous answer you can use Rails.application.routes.url_helpers on matching URLS just add in routes :as like the following example:

get "sessions/destroy/:param_id", as: :logout 

so you can use it as following:

Rails.application.routes.url_helpers.logout_path(:param_id => your_value)

This will do the same as url_for

Hopefully, this would help

Hussam Kurd
  • 8,066
  • 2
  • 43
  • 38