Grape::ActiveModelSerializers for models with compound names

should generate the proper 'root' node for individual objects
  should generate the proper 'root' node for serialized arrays of objects
This commit is contained in:
george 2013-04-30 14:20:18 -04:00
parent 94efb988f5
commit 8022de2d54
4 changed files with 41 additions and 4 deletions

View file

@ -48,7 +48,7 @@ module Grape
if options[:root] != false && serializer.root != false
# the serializer for an Array is ActiveModel::ArraySerializer
options[:root] ||= serializer.root || resource.first.class.name.downcase.pluralize
options[:root] ||= serializer.root || resource.first.class.name.underscore.pluralize
end
end
@ -61,4 +61,4 @@ module Grape
end
end
end
end
end

View file

@ -7,4 +7,12 @@ ActiveRecord::Schema.define(version: 20130403105356) do
t.datetime "created_at"
t.datetime "updated_at"
end
end
create_table "blog_posts", force: true do |t|
t.string "title"
t.string "body"
t.datetime "created_at"
t.datetime "updated_at"
end
end

View file

@ -53,6 +53,27 @@ describe Grape::ActiveModelSerializers do
last_response.body.should == "{\"users\":[{\"first_name\":\"JR\",\"last_name\":\"HE\"},{\"first_name\":\"JR\",\"last_name\":\"HE\"}]}"
end
context "for models with compound names" do
it "should generate the proper 'root' node for individual objects" do
subject.get("/home") do
BlogPost.new({title: 'Grape AM::S Rocks!', body: 'Really, it does.'})
end
get "/home"
last_response.body.should == "{\"blog_post\":{\"title\":\"Grape AM::S Rocks!\",\"body\":\"Really, it does.\"}}"
end
it "should generate the proper 'root' node for serialized arrays of objects" do
subject.get("/home") do
blog_post = BlogPost.new({title: 'Grape AM::S Rocks!', body: 'Really, it does.'})
[blog_post, blog_post]
end
get "/home"
last_response.body.should == "{\"blog_posts\":[{\"title\":\"Grape AM::S Rocks!\",\"body\":\"Really, it does.\"},{\"title\":\"Grape AM::S Rocks!\",\"body\":\"Really, it does.\"}]}"
end
end
# [User2Serializer, 'user2', :user2].each do |serializer|
# it "should render using serializer (#{serializer})" do
# subject.get("/home", serializer: serializer) do

View file

@ -6,4 +6,12 @@ end
class UserSerializer < ActiveModel::Serializer
attributes :first_name, :last_name
end
end
class BlogPost < ActiveRecord::Base
attr_accessor :title, :body
end
class BlogPostSerializer < ActiveModel::Serializer
attributes :title, :body
end