Using custom to_json method in nested objects

后端 未结 3 715
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 12:06

I have a data structure that uses the Set class from the Ruby Standard Library. I\'d like to be able to serialize my data structure to a JSON string.

By default, Set

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 12:39

    Here is my approach to getting to_json method for custom classes which most probably wouldn't contain to_a method (it has been removed from Object class implementation lately)

    There is a little magic here using self.included in a module. Here is a very nice article from 2006 about module having both instance and class methods http://blog.jayfields.com/2006/12/ruby-instance-and-class-methods-from.html

    The module is designed to be included in any class to provide seamless to_json functionality. It intercepts attr_accessor method rather than uses its own in order to require minimal changes for existing classes.

    module JSONable
      module ClassMethods
        attr_accessor :attributes
    
        def attr_accessor *attrs
          self.attributes = Array attrs
          super
        end
      end
    
      def self.included(base)
        base.extend(ClassMethods)
      end
    
      def as_json options = {}
        serialized = Hash.new
        self.class.attributes.each do |attribute|
          serialized[attribute] = self.public_send attribute
        end
        serialized
      end
    
      def to_json *a
        as_json.to_json *a
      end
    end
    
    
    class CustomClass
      include JSONable
      attr_accessor :b, :c 
    
      def initialize b: nil, c: nil
        self.b, self.c = b, c
      end
    end
    
    a = CustomClass.new(b: "q", c: 23)
    puts JSON.pretty_generate a
    
    {
      "b": "q",
      "c": 23
    }
    

提交回复
热议问题