Merge pull request #1 from george/proper_root_node_for_compound_model_names

Grape::ActiveModelSerializers for models with compound names
This commit is contained in:
jrhe 2013-04-30 11:33:24 -07:00
commit e98149adb5
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