-
-
Save endorfin/758833 to your computer and use it in GitHub Desktop.
RUBY: RoutesJs
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
# | |
# Rails 3 Version | |
# - ported to rails3 | |
# - optimize javascript | |
# | |
# setup/usage: | |
# 1. copy to RAILS_ROOT/app/middleware/ | |
# 2. application.rb ... config.middleware.use 'RoutesJs' | |
# 3. Layoutfile: <%= javascript_include_tag 'routes' %> | |
# 4. js usage: category_url({ slug:'test',format:'json', page:2 }) | |
# | |
# inspired by rails2 version - Aleksandr Koss (kossnocorp@gmail.com) https://gist.github.com/235086 | |
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 | |
host = "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}" | |
routes = Rails.application.routes.routes.collect do |route| | |
path = route.path | |
named_route = route.name | |
unless named_route.blank? | |
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, params) { | |
var path_copy = path; | |
for(var key in params) { | |
if (params.hasOwnProperty(key)) | |
{ | |
path_copy = path_copy.replace( | |
':' + key, | |
params[key] | |
); | |
} | |
} | |
return( | |
path_copy | |
.replace(/.:format/g, '') | |
.replace(/\\/:\\w+\\)/g, '') | |
.replace(/[(|)]|\\.$/g, '') | |
); | |
} | |
EOF | |
end | |
def route_function name, path | |
<<EOF | |
function #{name}(params) { return(rails_route('#{path}', params)); } | |
EOF | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment