That simplifies things a bit. Here it is for completeness:
--- myapp.rb ---
require 'rubygems'
require 'sinatra'
require 'json'
require 'widget'
get '/widgets.json' do
=A0 Widget.all.to_json
end
get '/widgets/:id.json' do
=A0 Widget.find(Integer(params[:id])).to_json
end
post '/widgets.json' do
=A0 item =3D JSON.parse(request.body.read)
=A0 Widget.create(item).to_s
end
--- widget.rb ---
# Rubbish model, not thread-safe!
class Widget
=A0 attr_accessor :id, :name,
rice
=A0 def initialize(params)
=A0 =A0 @id =A0 =A0=3D params["id"]
=A0 =A0 @name =A0=3D params["name"]
=A0 =A0 @price =3D params["price"]
=A0 end
=A0 def to_json(*a)
=A0 =A0 instance_variables.inject({}) { |h,v|
=A0 =A0 =A0 h[v.to_s[1..-1]] =3D instance_variable_get(v)
=A0 =A0 =A0 h
=A0 =A0 }.to_json(*a)
=A0 end
=A0 @all =3D []
=A0 @seq =3D 0
=A0 def self.all
=A0 =A0 @all
=A0 end
=A0 def self.add(item)
=A0 =A0 item.id =3D (@seq +=3D 1)
=A0 =A0 all << item
=A0 =A0 return @seq
=A0 end
=A0 def self.create(params)
=A0 =A0 add(new(params))
=A0 end
=A0 def self.find(id)
=A0 =A0 all.find { |item| item.id =3D=3D id }
=A0 end
end
Widget.create("name" =3D> "flurble", "price" =3D> 12.3)
Widget.create("name" =3D> "boing", "price" =3D> 4.56)
If you require 'json/add/rails' then you don't need to define your own
to_json method, but it also allows people to create arbitrary Ruby
objects on your machine (which makes me uncomfortable)