Sha256: 38a5f748298a51ac7ccd3efe29546ea635851e9b1224d6dd1e1be93e7a4de041

Contents?: true

Size: 931 Bytes

Versions: 5

Compression:

Stored size: 931 Bytes

Contents

require 'structure'

unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
  ::JSON::JSON_LOADED
  require 'json'
end

class Structure
  def self.json_create(object)
    object.delete('json_class')
    new(object)
  end

  def to_json(*args)
    klass = self.class.name
    { JSON.create_id => klass }.
      merge(@attributes).
      to_json(*args)
  end
end

if defined? ActiveSupport
  class Structure
    def as_json(options = nil)
      # create a subset of the attributes by applying :only or :except
      subset = if options
        if attrs = options[:only]
          @attributes.slice(*Array.wrap(attrs))
        elsif attrs = options[:except]
          @attributes.except(*Array.wrap(attrs))
        else
          @attributes.dup
        end
      else
        @attributes.dup
      end

      klass = self.class.name
      { JSON.create_id => klass }.
        merge(subset)
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
structure-0.12.0 lib/structure/json.rb
structure-0.11.0 lib/structure/json.rb
structure-0.10.0 lib/structure/json.rb
structure-0.9.0 lib/structure/json.rb
structure-0.8.0 lib/structure/json.rb