Sha256: 6d4e531684385269c542d90a88c5ffc759cb37aa2598fa25e42504c0cd889064

Contents?: true

Size: 894 Bytes

Versions: 1

Compression:

Stored size: 894 Bytes

Contents

module OpenAPI::Loader
  #
  # Loads data from [#source] file and strinfies all its keys
  # @private
  #
  class Reader
    extend Dry::Initializer
    extend ConstructorShortcut[:call] # class-level .call

    param :source

    def call
      stringify_keys(try_json || try_yaml)
    end

    private

    def raw
      @raw ||= begin
        uri  = URI source
        path = Pathname source
        uri.absolute? ? Net::HTTP.get(uri) : File.read(path)
      end
    end

    def stringify_keys(data)
      case data
      when Hash
        data.each_with_object({}) { |(k, v), o| o[k.to_s] = stringify_keys(v) }
      when Array then data.map { |item| stringify_keys(item) }
      else data
      end
    end

    def try_json
      JSON.load raw
    rescue JSON::ParserError
      nil
    end

    def try_yaml
      YAML.load raw
    rescue Psych::SyntaxError
      nil
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
open_api-loader-0.0.1 lib/open_api/loader/reader.rb