caching_presenter
caching_presenter copied to clipboard
Using to_json on presenter
Is it possible to use to_json where present_collection @items is being used?
I've noticed it wraps the standard ActiveRecord json with some additional fields and doesn't honor the standard to_json(:only => {}, :except => {}) params.
Can you give me an example of the code you'd like to write?
class Item < ActiveRecord::Base
validates_presence_of :title, :code
end
class ItemPresenter < CachingPresenter
presents :item
def code
@item.code.upcase
end
end
class ItemsController < ApplicationController
def index
@items = present_collection Item.all
respond_to do |format|
format.html do
flash[:notice] = "None found" if @items.empty?
end
format.json do
render :json => @items.to_json(:only => [:id, :title, :code])
end
end
end
end
require 'spec/spec_helper'
describe ItemsController do
describe "JSON search" do
it 'should return one found result' do
@item = Factory(:item, :title => "Title", :code => 'abc')
get 'index', :format => 'json'
@rendered = ActiveSupport::JSON.decode response.body
@rendered.size.should == 1
@found = @rendered.first['item']
@found['code'].should == 'ABC'
@found['title'].should == 'Title'
@found['id'].should == @item.id
end
end
end
This works for @items if it's not using present_collection