Collecting hashes into OpenStruct creates “table” entry

前端 未结 6 979
滥情空心
滥情空心 2021-02-04 05:46

Why this (evaluated in Rails console)

[{:a => :b}].collect {|x| OpenStruct.new(x)}.to_json

adds a \"table\" record in there?



        
6条回答
  •  遇见更好的自我
    2021-02-04 06:11

    Because @table is a instance variable of OpenStruct and Object#as_json returns Hash of instance variables.

    In my project, I implemented OpenStruct#as_json to override the behaviour.

    require "ostruct"
    class OpenStruct
      def as_json(options = nil)
        @table.as_json(options)
      end
    end
    

提交回复
热议问题