Skip to content

Instantly share code, notes, and snippets.

@djanowski
Created August 5, 2013 21:09
Show Gist options
  • Save djanowski/6159644 to your computer and use it in GitHub Desktop.
Save djanowski/6159644 to your computer and use it in GitHub Desktop.
require "cuba"
module Cuba::Routable
def self.setup(app)
app.define do
self.class.routes.each do |route, app|
on(route) { run(app) }
end
end
end
module ClassMethods
def routes
@routes ||= {}
end
def route(path, &block)
routes[path] = Class.new(self, &block)
end
end
end
if __FILE__ == $0
require "cuba/test"
# app.rb or even config.ru
Cuba.plugin Cuba::Routable
# Possibly routes/users.rb
Cuba.route("users") do
define do
on get do
res.write("All of the users")
end
end
end
# Possibly routes/posts.rb
Cuba.route("posts") do
define do
on get do
res.write("All of the posts")
end
end
end
scope do
test "routing" do
get "/users"
assert_equal last_response.body, "All of the users"
get "/posts"
assert_equal last_response.body, "All of the posts"
end
end
class API < Cuba
plugin Cuba::Routable
def ok
res.write("OK")
end
end
API.route("users") do
define do
on root do
ok
end
end
end
scope do
def app
API
end
test "subclasses the right class" do
get "/users"
assert_equal last_response.body, "OK"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment