Created
November 11, 2011 20:08
-
-
Save seancribbs/1359079 to your computer and use it in GitHub Desktop.
Combining Roar with Webmachine.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/setup' | |
require 'roar/representer/json' | |
require 'roar/representer/feature/hypermedia' | |
require 'webmachine' | |
class Product | |
include Roar::Representer::JSON | |
include Roar::Representer::Feature::Hypermedia | |
property :name | |
property :id | |
property :price | |
link :self do | |
"/products/#{id}" | |
end | |
# until Roar supports it | |
def from_json(json) | |
other = Product.from_json(json) | |
self.name = other.name | |
self.price = other.price | |
self | |
end | |
end | |
# We're in-memory ROFLSCALE | |
$products = [ | |
Product.from_attributes(:id => 1, | |
:name => "Nick's Awesomesauce", | |
:price => 10_000_000) | |
] | |
class ProductResource < Webmachine::Resource | |
def allowed_methods | |
if request.path_info[:id] | |
%w[GET HEAD] | |
else | |
%w[POST] | |
end | |
end | |
def resource_exists? | |
@product = $products[request.path_info[:id].to_i - 1] if request.path_info[:id] | |
[email protected]? | |
end | |
def allow_missing_post? | |
true | |
end | |
def post_is_create? | |
true | |
end | |
def create_path | |
@product = Product.from_attributes(:id => $products.length+1) | |
@product.to_json | |
@product.links[:self] | |
end | |
def content_types_provided | |
[["application/json", :to_json]] | |
end | |
def content_types_accepted | |
[["application/json", :from_json]] | |
end | |
def from_json | |
$products << @product.from_json(request.body.to_s) | |
end | |
def to_json | |
@product.to_json | |
end | |
end | |
Webmachine.routes do | |
add ["products"], ProductResource | |
add ["products", :id], ProductResource | |
end.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Needs some love (like me): https://github.com/apotonick/webmachinelovesroar