Lightweight web serviceswith Sinatra and RestClient
Adam Wiggins &Blake MizeranyRubyconf 2008
What for?
app lifecycle
Birth: small and beautiful
Fate: sprawling mess
web services
Rails?
Rails?
Too much.
Bare mongrel handler or Rack app?
Too little.
Bare mongrel handler or Rack app?
Sinatra - the classy microframework for Ruby
require 'rubygems'require 'sinatra'
get '/' do "Hello, whirled"end
$ ruby hello.rb
require 'rubygems'require 'sinatra'require 'lib/posts'
post '/posts' post = Post.create! params redirect "/posts/#{post.id}"do
get '/posts/:id' do @post = Post.find(params[:id]) erb :postend
‣Templating (erb, haml, builder)
‣Tests/specs (test/spec, rspec, test::unit)
‣Before filters‣Helpers‣Error handlers‣Inline templates‣Code reloading‣HTTP caching (etag, last-modified)
‣Rack / inline middleware
A commitment to small
A commitment to smallRails 87,990Merb-core 12,417Ramaze 11,796Camping 1,704Sinatra 1,576
Sinatra is a proud Ruby citizen
examples
git-wikihttp://github.com/sr/git-wiki
355 linesof Ruby
get '/:page' do @page = Page.find(params[:page]) haml :showend
__END__@@ layout%html %body %content=yield
@@ show%h1= title#page_content= @page.to_html
rifgrafhttp://github.com/adamwiggins/rifgraf
61 linesof Ruby
github-serviceshttp://github.com/pjhyett/github-services
423 linesof Ruby
scantyhttp://github.com/adamwiggins/scanty
194 linesof Ruby
client side
ActiveResource?
ActiveResource?
Too much.
Net::HTTP?
Net::HTTP?
Too little.
RestClient -the Sinatra-inspired microclient for Ruby
require 'rubygems'require 'rest_client'
RestClient.get 'http://localhost:4567/posts'
require 'rubygems'require 'rest_client'
RestClient.post 'http://localhost:4567/posts', :author => 'Me', :title => 'First Post'
$ restclient http://example.com>> post '/resource', :value => 42=> "result"
Console
$ restclient get http://example.com/posts > posts.xml
$ restclient post http://example.com/posts < post.xml
$ restclient put http://example.com/posts/1 < post.xml
$ restclient delete http://example.com/posts/1
A better curl
$ RESTCLIENT_LOG=stdout ruby myscript.rb
RestClient.get "http://example.com/posts"# => 200 OK | text/html 3781 bytes
RestClient.post "http://example.com/posts", "title=First+post"# => 200 OK | text/html 40 bytes
Logging & replay
examples
heroku-clienthttp://github.com/adamwiggins/heroku-client
couchresthttp://github.com/jchris/couchrest
principles
“lagom”
“lagom”
just the right amount
Fewer classes,less inheritance
Controller objectmapping & routes
URLs
vs.
Don’t fe
ar the U
RLs!Controller objectmapping & routes
URLs
vs.
Exposed simplicity instead ofhidden complexity
Small things,loosely joined,written fast
- Justin Gehtland @ Relevance
http://github.com/bmizerany/sinatra
Adam Wiggins &Blake MizeranyRubyconf 2008
http://rest-client.heroku.com/
http://adam.blog.heroku.com/