Created
December 28, 2014 10:37
-
-
Save sapslaj/890f1e6569566ad3b68f to your computer and use it in GitHub Desktop.
Client side URL helpers generated from Rails routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%= ClientRoutes.to_js %> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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