caching_presenter icon indicating copy to clipboard operation
caching_presenter copied to clipboard

Using to_json on presenter

Open johnlauck opened this issue 14 years ago • 3 comments

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.

johnlauck avatar Apr 23 '10 14:04 johnlauck

Can you give me an example of the code you'd like to write?

zdennis avatar Apr 23 '10 14:04 zdennis

    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

johnlauck avatar Apr 23 '10 14:04 johnlauck

This works for @items if it's not using present_collection

johnlauck avatar Apr 23 '10 15:04 johnlauck