sinatra-resources icon indicating copy to clipboard operation
sinatra-resources copied to clipboard

Simple nested resources to DRY up Sinatra code

= Sinatra::Resources - Simple nested resources for Sinatra

Ever wished you could do this in Sinatra?

resource 'posts' do get do # show all posts end

post do
  # create new post
end

end

resource 'posts/:id' do get do # show post params[:id] end

delete do
  # destroy post params[:id]
end

get 'comments' do
  # show this post's comments
end

end

Now you can.

This was inspired by {Sinatra ticket #31}[https://sinatra.lighthouseapp.com/projects/9779/tickets/31-nested-resources], which many people want but hasn't gotten traction to make it into Sinatra core. If you want it in Sinatra, pipe up on the ticket!

== Installation

Install +gemcutter+ if you don't have it:

sudo gem install gemcutter sudo gem tumble

Then just install this gem:

sudo gem install sinatra-resources

If you are using a classic (one-file) Sinatra app, just add:

require 'sinatra/resources'

If you are using a modular Sinatra::Base app, you must also add:

register Sinatra::Resources

To the top of your application class.

== Examples

Resources can be arbitrarily nested, and can be either string paths or symbols. There is also the shortcut +member+ which just maps to "resource ':id'". So you could also write the above example as:

resource :posts do get do # show all posts end

post do
  # create new post
end

member do
  get do
    # show post params[:id]
  end

  delete do
    # destroy post params[:id]
  end

  get :comments do
    # show this post's comments
  end
end

end

Or you can extract the "id" parameter as well:

resource :posts do get do # show all posts end

post do
  # create new post
end

member do
  get do |id|
    # show post ID=id
  end

  delete do |id|
    # destroy post ID=id
  end

  get :comments do |id|
    # show this post's comments
  end
end

end

Whatever blows your hair back.

== Author

Copyright (c) 2010 {Nate Wiger}[http://nate.wiger.org]. All Rights Reserved. Released under the {Artistic License}[http://www.opensource.org/licenses/artistic-license-2.0.php].