Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add rails route helpers to a class as class methods

How can i add rails route helpers like "root_path" to a class like my_model.rb as a class method?

So my class is like this:

Class MyModel

  def self.foo
    return self.root_path
  end

end

MyModel.foo

The above doesn't work because Class MyModel doesn't respond to root_path

This is what I know:

  1. I can use include Rails.application.routes.url_helpers, but that only add the module's methods as instance methods
  2. I tried doing extend Rails.application.routes.url_helpers but it didn't work

Please feel free to school me :)

like image 448
user566245 Avatar asked Jul 23 '13 16:07

user566245


1 Answers

URL routes shouldn't generally need to be accessed from a model. Typically you should only need to access them from your controller when handling a request, or when rendering a view (if you're e.g. formatting a link URL).

So instead of asking your model object for the root path, you would simply call root_path from within your controller or a view.

Edit

If you're just interested in the reason why you're unable to include the module's method as class methods in your class, I would not expect a simple include to work, since that would include the module's methods as as instance methods in your class.

extend would normally work, but in this case it does not due to how the url_helpers method is implemented. From actionpack/lib/action_dispatch/routing/route_set.rb source

def url_helpers
  @url_helpers ||= begin
    routes = self

    helpers = Module.new do
...
      included do
        routes.install_helpers(self)
        singleton_class.send(:redefine_method, :_routes) { routes }
      end

The included block containing the routes.install_helpers(self) call indicates that you will need to include the module in order to get the methods install (so extend is out).

The following should work if you call extend in the class context. Try this:

Class MyModel
  class << self
    include Rails.application.routes.url_helpers
  end
end
Class.root_path
like image 165
Stuart M Avatar answered Nov 03 '22 01:11

Stuart M