A Ruby DSL over Rack. You can create with it reusable web applications, suitable for both standalone and inside-Rails use.
Add this line to your application’s Gemfile:
gem 'hobby'
# or this if you want to use hobby master
# gem 'hobby', github: 'ch1c0t/hobby'
And then execute:
$ bundle
Or install it yourself as:
$ gem install hobby
To create a Hobby application, you create a class and include Hobby
in it.
For example:
require 'hobby'
class C
include Hobby
get "/hello" do
"Hello, world."
end
end
Then, you can create an instance of C
with
C.new
which will return a Rack application(an object which complies to Rack SPEC).
Because a Hobby application is just a Ruby class, you can do with it pretty much anything you would expect to be able to do with a Ruby class.
You can set some state in #initialize
and then use it in the route’s action:
class C
include Hobby
def initialize name
@name = name
end
get "/hello" do
"Hello, #{@name}."
end
end
class C
include Hobby
def initialize name
@name = name
end
def name
@name.upcase
end
get "/hello" do
"Hello, #{name}."
end
end
For common HTTP verbs, Hobby provides the route definers(methods named accordingly):
class App
include Hobby
get { 'Some string.' }
post { 'Some string.' }
put { 'Some string.' }
patch { 'Some string.' }
delete { 'Some string.' }
# TODO: find a good example for `options`
end
A definer should be called with a path(optional) and an action(passed as a block).
Calling a definer has a side effect of defining a route in the router.
When an incoming request matches a route,
the action is executed and a response is sent back to the client.
The return value of the action will be the body
of the response.
If a path was omitted
get do
'The body returned to the HTTP client making the request.'
end
the action is attached to the root route, like if
get '/' do
'The body returned to the HTTP client making the request.'
end
were called.
The following methods are predefined:
-
env
: aHash
, a Rack environment. -
request
: aRack::Request
. -
response
: aRack::Response
. -
route
: aHobby::Router::Route
, the currently executing route. -
route.params
, or a shortcutmy
: aHash
which stores route params. See Route params for a usage example. -
halt
: returns theresponse
immediately. See Halting for a usage example.
You can extend Hobby with usual modules:
module MyExtension
def do_something
# do something
end
end
class App
include Hobby
include MyExtension
get '/' do
do_something
'Hello World!'
end
end
-
hobby-json: JSON requests and responses.
-
hobby-auth: User authorization.
You can use map
and use
from Rack::Builder.
You can mount any Rack application to a Hobby application with map
.
Here is an example of mounting the application from Using #initialize
to '/anatoly' and '/patricio' routes:
class App
include Hobby
map '/anatoly', C.new('Anatoly')
map '/patricio', C.new('Patricio')
get '/' do
'Mapping app.'
end
end