我正在寻找一种简单的方法将装饰模型转换为json,以便在我的客户端模板中使用。我想找到一个解决方案,其中装饰模型的所有允许属性和公共方法将在json中保留。
目前我有使用rails后端的骨干RIA。我正在使用haml_coffee_assets gem进行客户端模板化。 Draper用于为我的用户模型提供装饰
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
我的控制器代码如下:
def index
@dialogs = ContactDecorator.decorate(current_user.contacts).collect{|c| c.for_json}
end
而且在我看来我只是初始化骨干应用程序:
:javascript
App.init({dialogs: #{@dialogs.to_json}})
有没有办法删除丑陋的#for_json装饰器方法?