Cuba + REST.
Add this line to your application's Gemfile:
gem 'crest'
And then execute:
$ bundle
Or install it yourself as:
$ gem install crest
Let's see an example:
require 'cuba'
require 'cuba/render'
require 'crest'
require 'tilt'
Cuba.plugin Cuba::Render
Cuba.plugin Crest
Cuba.define do
on 'articles' do
rest Article # asuming that you have an Article model.
end
end
That'll give you these routes:
GET /articles
: will render thelist
template (not provided), passing thearticles
variable.POST /articles
: will render thenew
template (not provided) ifarticle
is not valid (callingarticle.valid?
) or it'll create a newArticle
and redirect to/articles/:id
if valid.GET /articles/new
: will render thenew
template (not provided), passing thearticle
variable: a newly createdArticle
.GET /articles/:id
: will render theshow
template (not provided), passing thearticle
variable: an object retrieved by callingArticle[id]
.GET /articles/:id/edit
: will render theedit
template (not provided), passing thearticle
variable: an object retrieved by callingArticle[id]
.DELETE /articles/:id
: will delete the object and redirect to/articles
.PUT /articles/:id
: will render theedit
template (not provided) ifarticle
is not valid (callingarticle.valid?
) or it'll update the a newArticle
and redirect to/articles/:id
if valid.
Well, just send a block along with the class name, like this:
Cuba.define do
on 'articles' do
rest Article do
on get, 'something' do
res.write 'hello'
end
end
end
end
And that'll give you also this route: GET /articles/something
.
Quite easy!
Exercise: try to nest multiple rest
calls.
Well, every route has its own method. For instance, /articles
calls the
list_articles
method, which is defined when you call the rest
method. If
you want to overwrite the basic behavior (eg. paginate results), you can
overwrite the list_articles
method:
class App < Cuba
def list_articles
render 'list', articles: Article.published
end
define do
rest Article
end
end
Quite simple!
Defined methods are:
list_
create_
new_
show_
update_
delete_
edit_
There are a few assumptions made by crest:
- Your model must respond to
all
in order to retrieve a collection - Your model must respond to
[]
in order to retrieve one object - Your model must respond to
valid?
- Your model must respond to
save
- Your model must respond to
set_all
- Your model must respond to
all
That said, if you use Sequel, you're all set.
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
See the LICENSE.