Skip to content

Instantly share code, notes, and snippets.

@kematzy
Created June 2, 2009 02:55
Show Gist options
  • Save kematzy/121954 to your computer and use it in GitHub Desktop.
Save kematzy/121954 to your computer and use it in GitHub Desktop.
# Example of how to use multiple Routes in external files/modules
require 'rubygems'
require 'sinatra/base'
# set the root of the whole app
APP_ROOT = File.dirname(File.expand_path(__FILE__)) unless defined?(APP_ROOT)
require "sinatra-external_routes_example"
class MyApp < Sinatra::Base
register Sinatra::ExternalRoutesExample
set :public, "#{APP_ROOT}/public"
set :views, "#{APP_ROOT}/views"
get '/' do
"hello world"
end
# just dumps the available methods of MyApp, so that you can easily see the routes defined
get '/methods' do
"#{self.methods.sort.join(",\n<br>")}"
end
end #/class MyApp
MyApp.run!(:port => 4567) if __FILE__ == $0
require 'sinatra/base'
module Sinatra
# Sinatra ExternalRoutesExample module
#
# This is just an example of how to create neat Extensions with multiple Routes defined,
# and how to load/register other extensions within a single extension.
#
# Inspiration came from Hancock [http://github.com/atmos/hancock/]
#
module ExternalRoutesExample
module Helpers
# add your public helper methods here
def do_something
## here
end
private
def do_something_in_private
# shhh
end
end #/ Helpers
# add your general DSL methods here
def self.registered(app)
app.helpers ExternalRoutesExample::Helpers
# the configuration options here
app.set :foo, 'bar'
# load external Routes here..
# require 'path/to/external/routes'
app.register Sinatra::MyRoutes::Blog
app.register Sinatra::MyRoutes::Gallery
end #/ self.registered
end #/ ExternalRoutesExample
# optional, only works in Classic Sinatra apps, not inside MyApp < Sinatra::Base type of apps
# register(Sinatra::ExternalRoutesExample)
module MyRoutes
module Blog
def self.registered(app)
app.get '/blog' do
"hello from blog and foo is [#{options.foo}]"
end
app.get '/blog/article' do
'hello from blog article'
end
# ....
end
end #/module Blog
module Gallery
module Helpers
# any specific helpers inside here.
end #/module Helpers
def self.registered(app)
app.helpers Gallery::Helpers
app.get '/gallery' do
'hello from gallery'
end
app.get '/gallery/one' do
'hello from gallery one'
end
# ....
end
end #/module Gallery
end #/module MyRoutes
end #/ Sinatra
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment