Skip to content

Latest commit

 

History

History
85 lines (66 loc) · 2 KB

README.rdoc

File metadata and controls

85 lines (66 loc) · 2 KB

Sinatra-controllers

Sinatra routing done differently. Allows for clean organization across multiple sinatra routes files.

  • this has only been tested with ruby 1.9.2

  • redirect doesn’t work.. yet

Examples

Also see the fixtures folders for what’s used in the tests.

views/index.haml

<!DOCTYPE HTML>
%html
  %head
    %meta(http-equiv="content-type" content="text/html; charset=utf-8")

    %title test page
%body
  fly away with sinatra controllers

You can divide your routes cleanly between as many classes as you please. At any time, you can also simply revert back to the plain vanilla sinatra syntax on use get at the top level.

sinatra_controller.rb

#!/usr/bin/env ruby

require 'sinatra'
require 'sinatra-controllers'

class Welcome < Sinatra::Controller
  def index
    haml :index
  end

  # this create a route corresponding to `get '/welcome/about'`
  # making it a shortcut for common routes. It doesn't handle arguments
  # unlike the block syntax.
  def get_about
    'making controllers in sinatra easy'
  end
end

Sinatra::Controllers.register Welcome do
  get '/', :index
end

This is a trick for common requests that don’t require arguments. It creates a route corresponding to ‘get ’/welcome/about’‘ in the flavor of Test::Unit where it uses the prefix before the underscore for the route type. The block to register is optional here.

class Welcome < Sinatra::Controller
  def get_about
    'making controllers in sinatra easy'
  end
end

You can also use scopes for your own defined path, either because you’re unhappy with your classname, or because you just want to:

class Fringe < Sinatra::Controller
  def get_walternet
    'scopes'
  end
  def peter
    'more scopes'
  end
  def index
    'index still if you want'
  end
end

Sinatra::Controllers.register(Fringe, :scope => 'fringe') do
  get 'peter', :peter
  get '/', :index
end

this enables the following routes

get '/fringe/walternet'
get '/fringe/peter'
get '/'