【问题标题】:Using RABL with Draper to render to_json使用 RABL 和 Draper 来渲染 to_json
【发布时间】:2012-04-13 16:08:42
【问题描述】:

我的Ticket 模型的应用程序中有一些相当复杂的JSON 响应,我希望我的TicketDecorator 能够构建这些响应。

但是,我已经为我的系统设置了 API 并使用 RABL 来构建这些 JSON 响应,所以我想重用我已经创建的模板。

我想知道是否可以从 TicketDecorator 内部的方法中呈现 RABL 模板,如下所示:

这是我的 RABL 模板tickets/show.json.rabl

object @ticket

attributes :id, :link, :reported_ago_in_words_with_reporter,
           :last_updated_in_words_with_updater, :priority_label, :status,
           :location, :category_list

node(:attachment_urls) { |ticket| [ asset_path(ticket.first_attachment_url),     asset_path(ticket.second_attachment_url), asset_path(ticket.third_attachment_url) ] }

node(:comment_count) { |ticket| ticket.comments.count }

child :recent_comments do
  extends 'comments/index'
end

这是我的TicketDecorator 方法:

class TicketDecorator < ApplicationDecorator
  def as_json
    h.render(template: "tickets/show", formats: :json)
  end
end

但是,这不起作用,因为我无法成功设置@ticket,并且我收到一条错误消息:undefined method `first_attachment_url' for nil:NilClass 因为@ticket 为零。

关于如何让这两者很好地协同工作,有人有什么好的解决方案吗?

我唯一真正的想法是将模板渲染为字符串并手动使用 RABL,但我不确定如何在 Draper 中调用 render_to_string,因为它不是视图助手。

对此有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby decorator rabl draper


    【解决方案1】:

    如果是访问 Rabl 中的对象,this 可能对您有所帮助。

    此外,在您的自定义节点上,我将直接访问对象,而不是依赖块变量。后者是 imo 用于处理集合,如下所示:

    collection @tickets
      attribute :name
      node(:some_complex_stuff) {|ticket| ticket.vendor.heavy_lifting}
    

    你也可以看看这样一个事实,你可以像属性一样调用任何对象方法,因为它仍然是 Ruby :)

    class Ticket
      def we_got_what
        "the funk!"
      end
    end
    

    为了让你的 Rabl 变得时髦,只需这样做:

    object @ticket
     attribute :we_got_what
    

    【讨论】:

      【解决方案2】:

      现在有一个 rabl wiki 条目描述了这种情况。对于其他到达的人,check it out here

      解决方案是将装饰器发送给 rabl,而不是从装饰器渲染 rabl。推卸责任让事情变得容易一些。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-12
        • 2012-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-22
        • 1970-01-01
        相关资源
        最近更新 更多