3

I'm looking for an easy way to convert decorated model into json to use in my client-side templates. I'd like to find a solution where all allowed attributes and public methods of the decorated model will persist in json.

Currently I have backbone RIA with rails backend. I'm using haml_coffee_assets gem for client-side templating. Draper is there to provide decoration for my User model

class ContactDecorator < Draper::Base

  include Draper::LazyHelpers

  decorates :user

  allows :login, :id, :total_unread, :total_messages

  def for_json
    {
        :new_messages => new_messages,
        :avatar_link => avatar_link,
        :login_name_link => login_name_link,
        :id => model.id,
        :name => model.login,
        :avatar => model.avatar.url(:small),
        :humanized_messages_number =>
    }
  end

  def  humanized_messages_number
    pluralize(user['total_messages'], t("share_my_trip.messages.Message"), t("share_my_trip.messages.Messages")) + " #{new_messages}"
  end

  def new_messages
    model['total_unread'].to_i > 0 ? "(#{model['total_unread'].to_i} #{t("share_my_trip.messages.new")})" : ''
  end

  def avatar_link
    link_to(image_tag(model.avatar.url(:small), :size => "32x32", :onerror => "this.src='/avatars/original/missing.png'"), share_my_trip_user_path(:id => model.login), :id => "user-nick-#{model.id}", :class => "author")
  end

  def login_name_link
    link_to(model.login, share_my_trip_user_path(:id => model.login), :id => "user-nick-#{model.id}", :class => "author")
  end

end

my controller code looks like:

def index
  @dialogs = ContactDecorator.decorate(current_user.contacts).collect{|c| c.for_json}
end

and than in my view I'm just initializing backbone app:

:javascript
  App.init({dialogs: #{@dialogs.to_json}})

Is there a way to delete ugly #for_json decorator method?

Ortepko
  • 371
  • 1
  • 10

0 Answers0