https://github.com/mynyml/simple_router
Simple rack router
https://github.com/mynyml/simple_router
Last synced: 9 months ago
JSON representation
Simple rack router
- Host: GitHub
- URL: https://github.com/mynyml/simple_router
- Owner: mynyml
- License: mit
- Created: 2009-05-18T18:43:36.000Z (about 17 years ago)
- Default Branch: master
- Last Pushed: 2015-07-31T16:48:00.000Z (about 11 years ago)
- Last Synced: 2025-11-12T01:39:26.947Z (9 months ago)
- Language: Ruby
- Homepage:
- Size: 136 KB
- Stars: 28
- Watchers: 2
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-sinatra - SimpleRouter - Small and simple standalone router, meant for (Routers)
- awesome-rack - SimpleRouter
README
Summary
-------
Small and simple standalone router, meant for use with Rack applications.
Features
--------
* Familiar Sinatra-like DSL for defining actions
* Modular architecture (see ROUTING ENGINES section)
* No magic
* Low level / Highly flexible
* Simple code
Examples
--------
class App
include SimpleRouter::DSL
get '/' do
'home'
end
get '/archives/:year/:month/:day' do |year, month, day|
Article.archived.find_by_date(year, month, day)
end
def call(env)
verb, path = ENV['REQUEST_METHOD'], ENV['PATH_INFO']
route = self.class.routes.match(verb, path)
route.nil? ?
[404, {'Content-Type' => 'text/html'}, '404 page not found'] :
[200, {'Content-Type' => 'text/html'}, route.action.call(*route.values)]
end
end
The SimpleRouter::DSL mixin provides 5 class methods:
#get, #post, #put, #delete and #routes
The four verb methods allow you to define actions that will match a request for
the verb and route signature it defines.
The `#routes` method responds to `#match` and will return the first matching
route (in order they were defined). The route returned is a simple object; for
the second route in the example above, you get:
route.verb #=> :get
route.path #=> '/archives/:year/:month/:day'
route.action #=> lambda {|year, month, day| Article.archived.find_by_date(year, month, day) }
route.values #=> ['2008', '07', '01'] # after being matched with path '/archives/2008/07/01'
See examples/ directory for executable code examples.
Routing Engines
---------------
By design, the code is seperated in two main components:
* DSL for defining routes/actions and retrieving requested action block.
* Routing engine
Different engines can be used by assigning them to the router:
SimpleRouter.engine = UltraFastEngine
This allows, for instance, a new faster engine to be used by an app without
changes in the top level DSL.
Engines can also allow route definitions to include more (or less!) features.
For example, the built-in SimpleEngine allows route variables and extension
handling. Others could add variable conditions (`:id => Integer`), mime-type
restrictions, etc.
### Engine Writers
Engines only need to conform to a simple interface. See
lib/simple_router/engines/simple_engine.rb for details.