【问题标题】:Writing a service object that returns JSON only编写仅返回 JSON 的服务对象
【发布时间】:2014-09-14 02:03:01
【问题描述】:

我正在尝试编写一个名为JSONDocument 的服务对象,该对象在多个条件等中仅返回JSON。到目前为止,它看起来像这样:

# encoding: utf-8
#
class JSONDocument
  attr_reader :components, :cover, :introduction, :photo, :title, :user, :variables

  def initialize(document)
    @document = document
    components if @document.template.component_count > 0
  end

  private

  def user
    if @document.ap?
      self[:user] = @document.ap_info.gsub("\r\n", "\n")
    else
      self[:user] = @document.no_ap.gsub("\r\n", "\n")
    end
  end

  def variables
    u = []
    @document.template_variables.each do |v|
      u << v.heading_and_body
    end
    u
  end

  def extension(file)
    File.extname(file)
  end

  def components
    components = []
    @document.publications.rank(:position).each do |p|
      components << { component_id: p.component.id,
                      component_page_count: p.component.page_count || 1 }
    end
    self << components
  end

  def cover
    if @document.template.has_covers?
      self[:cover] = "#{@document.cover.id}#{extension(@document.cover.cover_file_name)}"
    else
      self[:cover] = ''
    end
  end

  def introduction
    if @document.template.has_introductions?
      self[:introduction] = message.gsub("\r\n\r\n", "\r\n")
    else
      self[:introduction] = ''
    end
  end

  def photo
    if @document.photo
      self[:photo] = "#{@document.photo.id}#{extension(@document.photo.photo_file_name)}"
    else
      self[:photo] = ''
    end
  end

  def title
    @document.template.has_title ? self[:title] = title : self[:title] = ''
  end
end

但我不太确定如何向对象添加元素以访问如下信息:

json = JSONDocument.new(@document)
json[:title] => 'Some title of @document'

任何帮助都会很棒。谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-3 hash


    【解决方案1】:

    编写一个模拟哈希访问风格的方法,如下所示:

    def [](key)
      raise "An error occurred" if ... #some validation to filter trash
      self.send(key)
    end
    

    当然,它只会提供对对象属性的访问(获取但不设置)。

    【讨论】:

    • 但是,为了增加复杂性,如果我希望对象返回由上面列出的属性构建的哈希值,而不是一次只返回一个呢?
    • 我写了这个:def to_hash {}.tap do |h| @@attributes.each { |k, v| h[k.to_sym] = self.send(k) } end end
    • 它不是动态的。创建的每个新属性都意味着您必须更改属性数组。
    • 如果您需要更多类似的功能,只需使用 OpenStruct:ruby-doc.org/stdlib-1.9.3/libdoc/ostruct/rdoc/OpenStruct.html
    • 不,不是,这有点烦人,但在这种情况下,它不可能是完全动态的。另外,我不知道如何实现OpenStruct
    猜你喜欢
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2018-12-20
    相关资源
    最近更新 更多