From 9094b8b0b6c850bc6a1f4b7dc564fdc852dcd0f0 Mon Sep 17 00:00:00 2001 From: Micha Wrobel Date: Sat, 3 Mar 2012 18:09:03 +0100 Subject: [PATCH] Override as_json to include more data --- app/models/comment.rb | 15 +++++++++++++++ spec/models/comment_spec.rb | 26 ++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/app/models/comment.rb b/app/models/comment.rb index 6cae84a..92b81fb 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -9,4 +9,19 @@ class Comment < ActiveRecord::Base attr_accessible :body + def created + created_at.to_s + end + + def as_json(options = {}) + super({ + :include => { + :user => { + :only => [ :nickname, :avatar_url ] + } + }, + :methods => [:created] + }.merge(options)) + end + end diff --git a/spec/models/comment_spec.rb b/spec/models/comment_spec.rb index 37d7c7d..57525a5 100644 --- a/spec/models/comment_spec.rb +++ b/spec/models/comment_spec.rb @@ -5,4 +5,30 @@ describe Comment do it "factory should be valid" do Factory.build(:comment).should be_valid end + + describe "#as_json" do + let(:user) { Factory(:user) } + let(:comment) { Factory.build(:comment) } + + before do + comment.user = user + end + + it "should include user.gravatar_url" do + hash = comment.as_json + hash.should include(:user) + hash[:user].should include("avatar_url") + end + + it "should include user.nickname" do + hash = comment.as_json + hash.should include(:user) + hash[:user].should include("nickname") + end + + it "should include comment.created" do + comment.as_json.should include :created + end + end + end