编写仅返回JSON的服务对象

时间:2014-07-23 03:01:02

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

我正在尝试编写一个名为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'

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

1 个答案:

答案 0 :(得分:1)

编写一个模拟散列访问方式的方法,如下所示:

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

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