Sha256: 355af5113b2c71c1105f2972322fccbc8044fedd8996284277fcfbff8ae8526d

Contents?: true

Size: 1.9 KB

Versions: 6

Compression:

Stored size: 1.9 KB

Contents

require_relative "./data_structures/string"
require_relative "./data_structures/number"

module JsonTestData
  class JsonSchema
    attr_accessor :schema

    def initialize(schema)
      @schema = JSON.parse(schema, symbolize_names: true)
    end

    def generate_example
      generate(schema).to_json
    end

    private
      def generate_data(obj)
        case obj.fetch(:type)
        when "number"
          JsonTestData::Number.create(obj)
        when "integer"
          JsonTestData::Number.create(obj)
        when "boolean"
          true
        when "string"
          JsonTestData::String.create(obj)
        end
      end

      def generate(obj)
        if is_object?(obj)
          generate_object(obj)
        elsif is_array?(obj)
          generate_array(obj)
        else
          generate_data(obj)
        end
      end

      def is_object?(property)
        property.fetch(:type, nil) == "object"
      end

      def is_array?(property)
        property.fetch(:type, nil) == "array"
      end

      def generate_object(object)
        obj = {}

        if object.has_key?(:properties)
          object.fetch(:properties).each do |k, v|
            obj[k]  = nil unless v.has_key?(:type)

            obj[k]  = generate(v)
          end
        end

        if object.has_key?(:minProperties) && obj.length < object.fetch(:minProperties, 0)
          (object.fetch(:minProperties) - obj.length).times do
            key = JsonTestData::String.create({type: "string"})
            obj[key] = nil
          end
        end

        obj.size == 0 ? {} : obj
      end

      def generate_array(object)
        object.fetch(:minItems, nil) || object[:minItems] = 1

        if object.fetch(:items, nil) && object.fetch(:items).has_key?(:type)
          Array.new(object.fetch(:minItems), generate(object.fetch(:items))).compact
        else
          Array.new(object.fetch(:minItems))
        end
      end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
json_test_data-0.6.0 lib/json_test_data/json_schema.rb
json_test_data-0.5.1 lib/json_test_data/json_schema.rb
json_test_data-0.5.0 lib/json_test_data/json_schema.rb
json_test_data-0.4.0 lib/json_test_data/json_schema.rb
json_test_data-0.4.0.beta lib/json_test_data/json_schema.rb
json_test_data-0.3.0.beta lib/json_test_data/json_schema.rb