Permalink
Browse files

Add support for OPTIONS, query_type in index, and 400 error for inval…

…id type.
  • Loading branch information...
1 parent 108c711 commit d2ab0a42c248edf4c416fff4edc3d48d91dcd481 Yehuda Katz committed Jul 17, 2008
@@ -2,14 +2,33 @@ class MerbRestServer::Rest < MerbRestServer::Application
provides :json
before do
- @type = Object.full_const_get(params[:type].camel_case)
+ begin
+ @type = Object.full_const_get(params[:type].camel_case)
+ rescue NameError, NoMethodError
+ throw :halt, display({}, :status => 400)
+ end
+ end
+
+ def options
dkubb
dkubb Jul 21, 2008

OPTIONS should return the actual methods that are allowed for the requested URI. So, assuming standard routes, GET,POST on /:controller/ and GET,PUT,DELETTE on /:controller/:id

+ headers["Allow"] = "GET, PUT"
+ display @type.properties.inject({}) {|a,x| a[x.name] = x.type; a }
end
+ # Index supports:
+ # /rest/foo
+ # /rest/foo?id=1,2
+ # /rest/foo?name=he%25&query_type=like
+ #
+ # Query type specifies what kind of query to use:
+ # /rest/foo?name=he%25&query_type=like
+ # becomes:
+ # Foo.all(:name.like => "he%")
def index
types = @type.properties.map {|x| x.name}
+ query_type = params[:query_type] || :eql
hsh = {}
types.each do |type|
- hsh[type] = params[type].split(",") if params[type]
+ hsh[type.send(query_type)] = params[type].split(",") if params[type]
end
display @type.all(hsh)
end
@@ -14,6 +14,14 @@
require File.dirname(__FILE__) + '/../spec_helper'
+ describe "Incorrect type" do
+ it "returns a 400 error (Bad Request)" do
+ controller = get("/rest/zoo", {}, :http_accept => "application/json")
+ controller.status.should == 400
+ controller.body.should == "{}"
+ end
+ end
+
describe "GET index" do
describe "plain index" do
before do
@@ -39,6 +47,20 @@
controller = get("/rest/foo", {:name => "Mock1"}, :http_accept => "application/json")
controller.body.should == Foo.all(:name => "Mock1").to_json
end
+
+ it "supports providing the type of query" do
+ controller = get("/rest/foo", {:name => "Mock%", :query_type => "like"}, :http_accept => "application/json")
+ controller.body.should == Foo.all(:name.like => "Mock%").to_json
+ end
+ end
+ end
+
+ describe "OPTIONS on a resource" do
+ describe "when the resource exists" do
+ it "returns back the schema in JSON form" do
+ @controller = request("/rest/foo/1", {}, :http_accept => "application/json", :request_method => "OPTIONS")
+ @controller.body.should == Foo.properties.inject({}) {|a,x| a[x.name] = x.type; a }.to_json
+ end
end
end
@@ -17,4 +17,4 @@ class Foo
Foo.create(:name => "Mock1")
Foo.create(:name => "Mock2")
-Foo.create(:name => "Mock3")
+Foo.create(:name => "Moc3")

0 comments on commit d2ab0a4

Please sign in to comment.