Skip to content

Instantly share code, notes, and snippets.

@docunext
Forked from kossnocorp/routes_js.rb
Created September 6, 2012 17:56
Show Gist options
  • Save docunext/3658986 to your computer and use it in GitHub Desktop.
Save docunext/3658986 to your computer and use it in GitHub Desktop.
# Hi! I'am rack middleware!
# I was born for show right way to you JavaScript
# My author's name was Aleksandr Koss. Mail him at kossnocorp@gmail.com
# Nice to MIT you!
require(File.dirname(__FILE__) + '/../config/environment') unless defined?(Rails)
class RoutesJs
def initialize app, options = {}
@app = app
@options = options
end
def call env
if env['PATH_INFO'] =~ /^\/javascripts\/routes.js$/
response = rails_route_function
routes = ActionController::Routing::Routes.routes.collect do |route|
host = "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}"
path = route.segments.inject('') { |str,s| str << s.to_s }
named_route = ActionController::Routing::Routes.
named_routes.routes.index(route).to_s
if named_route != ''
response << route_function("#{named_route}_path", path)
response << route_function("#{named_route}_url", host + path)
end
end
[200, {'Content-Type' => 'application/javascript'}, [response]]
else
@app.call env
end
end
private
def rails_route_function
<<EOF
function rails_route(path, var_pairs) {
var pair_index = 0,
path_copy = path;
for(; pair_index < var_pairs.length; pair_index++) {
path_copy = path_copy.replace(
':' + var_pairs[pair_index][0],
var_pairs[pair_index][1]
);
}
return(
path_copy
.replace(/[(][.]:.+[)][?]/g, '')
.replace(/[(]|[)][?]/g, '')
);
}
EOF
end
def route_function name, path
<<EOF
function #{name}(variables) {
var var_pairs = [];
for(var key in variables) {
var_pairs.push([key, variables[key]]);
}
return(rails_route('#{path}', var_pairs));
}
EOF
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment