Skip to content

Instantly share code, notes, and snippets.

@mfojtik
Created January 7, 2013 21:13
Show Gist options
  • Save mfojtik/4478472 to your computer and use it in GitHub Desktop.
Save mfojtik/4478472 to your computer and use it in GitHub Desktop.
An example of 'slices' implementation in 37 lines of pure Sinatra.
require 'sinatra/base'
module Sinatra
module Slice
def self.prefix_routes(middleware)
prefix = prefix_from(middleware)
middleware.instance_eval {
@routes.each do |http_method, _|
@routes[http_method].each_with_index do |route, index|
original_route = route.shift.source[1..-1]
@routes[http_method][index] = [
Regexp.compile('^/' + prefix + (original_route == "/$" ? '$' : original_route))
] + route
end
end
}
middleware
end
private
def self.prefix_from(klass)
klass.name.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase.split('_')[0..-2].join('\/')
end
end
class Base
class << self
alias_method :original_use, :use
def use(middleware, *args, &block)
original_use(Slice.prefix_routes(middleware), *args, &block)
end
end
end
end
class UserProfilesModule < Sinatra::Base
# GET /user/profiles
get '/' do
'index action'
end
# GET /user/profiles/:id
get '/:id' do
'show action'
end
# GET /user/profiles/:id/edit
get '/:id/edit' do
'edit action'
end
end
class TestApp < Sinatra::Base
use UserProfilesModule
# GET /
get '/' do
'Hello from index app'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment