Skip to content

Instantly share code, notes, and snippets.

@sapslaj
Created December 28, 2014 10:37
Show Gist options
  • Save sapslaj/890f1e6569566ad3b68f to your computer and use it in GitHub Desktop.
Save sapslaj/890f1e6569566ad3b68f to your computer and use it in GitHub Desktop.
Client side URL helpers generated from Rails routes
<%= ClientRoutes.to_js %>
class ClientRoutes
attr_reader :routes
def initialize
@routes = []
Rails.application.routes.routes.each do |route|
@routes.push ActionDispatch::Routing::RouteWrapper.new(route)
end
@routes
end
def self.to_js(options={})
as = options[:as] || :path
final_js = ""
routes = ClientRoutes.new.routes
routes.reject! { |r| r.internal? || r.engine? || r.name.empty? }
# Voodoo starts here
routes.each do |route|
arguments = []
return_statement = "return "
route.path.gsub(/\(.:format\)/, '').split('/').each do |url_part|
next if url_part.empty?
if url_part[0] == ':'
argument = url_part.tr(':', '')
arguments << argument
return_statement << "\"/\" + #{argument}"
else
return_statement << "\"/#{url_part}\""
end
return_statement << " + "
end
return_statement << "\"\";"
template_renderer = ERB.new("var <%= route.name %>_<%= as %> = function (<%= arguments.join(', ') %>) {<%= return_statement %>};")
final_js << template_renderer.result(binding)
end
final_js
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment