Skip to content

Instantly share code, notes, and snippets.

@hukl
Created October 11, 2009 09:43
Show Gist options
  • Save hukl/207573 to your computer and use it in GitHub Desktop.
Save hukl/207573 to your computer and use it in GitHub Desktop.
# put this in RAILS_ROOT/lib
module AccessToken
class << self
def current=(token)
Thread.current[:token] = token
end
def current
Thread.current[:token] ||= ""
end
end
end
# put this in RAILS_ROOT/lib/routing_filter
require 'i18n'
require 'routing_filter/base'
module RoutingFilter
class Token < Base
def around_recognize(path, env, &block)
token = extract_token!(path) # remove the token from the beginning of the path
returning yield do |params| # invoke the given block (calls more filters and finally routing)
params[:token] = token if token # set recognized token to the resulting params hash
end
end
def around_generate(*args, &block)
token = args.extract_options!.delete(:token) # extract the passed :token option
token = AccessToken.current if token.nil? # default to I18n.token when token is nil (could also be false)
returning yield do |result|
if token
url = result.is_a?(Array) ? result.first : result
prepend_token!(url, token)
end
end
end
protected
def extract_token!(path)
path.sub! /([a-z\d]+\-[a-z\d]+\-[a-z\d]+\-[a-z\d]+\-[a-z\d]+)\//, ''
$1
end
def prepend_token!(url, token)
url.sub!(%r(^(http.?://[^/]*)?(.*))) { "#{$1}/#{token}#{$2}" }
end
end
end
# put this in your application_controller
before_filter :set_token
protected
def set_token
AccessToken.current = params[:token].to_sym if params[:token]
end
# add this to your routes.rb
map.filter :token
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment