代码之家  ›  专栏  ›  技术社区  ›  t56k

编写仅返回JSON的服务对象

  •  0
  • t56k  · 技术社区  · 10 年前

    我正在尝试编写一个服务对象,名为 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 回复  |  直到 10 年前
        1
  •  1
  •   Tiago Farias    10 年前

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

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

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