我正在尝试编写一个服务对象,名为
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'
任何帮助都会很棒。谢谢