ruby 用于创建封装JSON序列化逻辑的类的简单模式。只需继承`BaseSerializer`并覆盖h

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 用于创建封装JSON序列化逻辑的类的简单模式。只需继承`BaseSerializer`并覆盖h相关的知识,希望对你有一定的参考价值。

# serialize a comment to json:
# 
#   CommentSerializer.new(c).as_json
#   => {
#	"id"=>1,
#	"html_body"=>"lorem ipsum dolor...",
#	"created_at"=>"2013-07-26T10:38:47-07:00",
#	"user"=>{
#		"id"=>1,
#		"name"=>"Matthew"
#	}
#    }
class CommentSerializer < BaseSerializer

  private

    def serialize(object, options={})
      super(object, options).tap do |json|
        json['link'] = user_path(serialized_object)
      end
    end

    def attributes
      %w(id created_at)
    end

    def includes
      { 'user' => { 'only' => %w(id name) } }
    end

    def methods
      %w(html_body)
    end
end
# An abstract base class used to create simple serializers
# for ActiveRecord objects
class BaseSerializer
  include Rails.application.routes.url_helpers

  attr_reader :serialized_object

  def initialize(serialized_object)
    @serialized_object = serialized_object
  end
	
  def as_json(options={})
    if serialized_object.respond_to?(:to_ary)
      serialized_object.map { |object| serialize(object, options) }
    else
      serialize(serialized_object, options)
    end
  end

  private

    # serialize a single instance
    def serialize(object, options={})
      object.as_json(as_json_options.merge(options))
    end

    # the default options passed to as_json
    def as_json_options
      { :only    => attributes, 
        :methods => methods, 
        :include => includes }
    end

    # hook methods
    def attributes ; end
    def includes   ; end
    def methods    ; end
end

以上是关于ruby 用于创建封装JSON序列化逻辑的类的简单模式。只需继承`BaseSerializer`并覆盖h的主要内容,如果未能解决你的问题,请参考以下文章

ruby 创建自己的类的解决方案

找不到使用 Json 的类的序列化程序

如何正确地将 JSON 字符串反序列化为包含另一个类的嵌套列表的类

Java编程的逻辑 (63) - 实用序列化: JSON/XML/MessagePack

(63) 实用序列化: JSON/XML/MessagePack / 计算机程序的思维逻辑

杰克逊错误:没有适合简单类的构造函数