Skip to content

Instantly share code, notes, and snippets.

@foca
Created February 26, 2012 21:55
Show Gist options
  • Save foca/1919174 to your computer and use it in GitHub Desktop.
Save foca/1919174 to your computer and use it in GitHub Desktop.
# Is this a bad idea? I really dislike having to type
# Rails.application.routes.url_helpers.foo_path in my javascript templates.
#
# This turns it into SomeApp.routes.foo_path, which still is a bit much, but
# means it's less work.
module SomeApp
# Public: Shortcut to access named routes when needed. This is targeted at
# asset-pipeline templates, so we can use these helpers from javascript
# without all the ceremony.
#
# Returns a module with the route helpers as singleton methods.
def self.routes
Rails.application.routes.url_helpers
end
end
@lagartoflojo
Copy link

How about:

class Routes
  def self.method_missing(helper, *args, &block)
    Rails.application.routes.url_helpers.send helper, args
  end
end

And then you can do Routes.foo_path.

@foca
Copy link
Author

foca commented Feb 27, 2012

That's slower (method_missing is a lot slower than dispatching methods), and it's the same approach at heart, so it's still not something I like a lot. I was thinking something along the way of including a routes helper method in the sprockets environment that delegates to this object. Then I would do something like:

<a href="{{ expand "<%= routes.foo_path("{foo}") %>" }}"></a>

Which feels slightly less hacky than

<a href="{{ expand "<%= SomeApp.routes.foo_path("{foo}") %>" }}"></a>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment