-
Notifications
You must be signed in to change notification settings - Fork 43
ruby_one_minute
This is a one minute guide to get you going with Restfulie Ruby. As soon as you finish this example you are up to the next guide and then move on to the features you want to explore more.
Configuration should always be minimal and programmatic. To use Restfulie simply install its gem:
gem install restfulie
Or require it in your gemfile:
require 'restfulie'
In your controller, simply tell what is your resource and which representation media types you support. Notice how every feature is nothing but a one-liner:
class ItemsController
respond_to :xml, :json, :atom
def index
respond_with @items = Item.all
end
def show
respond_with @item = Item.find(params[:id])
end
end
Rail's webservices support through CRUD xml/json/atom is a nice easy to use feature. To move from webservices into the rest world, let's add some hyperlinks. Creating a template file called index.tokamak, one describes a representation's appearance:
collection(@items, :root => "items") do |items|
items.link "self", items_url
items.members(:root => "item") do |m, item| # setting :root is unnecessary here but is iseful for customizing element names.
m.link :self, item_url(item)
m.values { |values|
values.name item.name
}
end
end
And our show.tokamak:
member(@item) do |m|
m.link "self", item_url(@item)
m.values { |v|
v.name @item.name
v.price @item.price
}
end
We are ready to go, hypermedia supported:
# using restfulie as an http api:
response = Restfulie.at('http://localhost:8080/items').accepts("application/xml").get
puts response.body
puts response.code
# unmarshalling the items response
items = response.resource
puts items.size
puts items[0].name
# navigating through hypermedia
item = { :name => "New product", :price => 30 }
result = items.link("self").follow.post item
puts result.code
This is it. Adding hypermedia capabilities and following links. Now its time to use it in the right way.