Sha256: a2628da56a09a21a9356be5a1a06a7c24bd406c370251d4a38f94355a8651cc2

Contents?: true

Size: 1018 Bytes

Versions: 2

Compression:

Stored size: 1018 Bytes

Contents

# frozen_string_literal: true
module DiscourseApi
  module API
    def self.params(args)
      Params.new(args)
    end

    class Params
      def initialize(args)
        raise ArgumentError.new("Required to be initialized with a Hash") unless args.is_a? Hash
        @args = args
        @required = []
        @optional = []
        @defaults = {}
      end

      def required(*keys)
        @required.concat(keys)
        @required.each do |k|
          raise ArgumentError.new("#{k} is required but not specified") unless @args.key?(k)
        end
        self
      end

      def optional(*keys)
        @optional.concat(keys)
        self
      end

      def default(args)
        args.each { |k, v| @defaults[k] = v }
        self
      end

      def to_h
        h = {}

        @required.each { |k| h[k] = @args[k] }

        @optional.each { |k| h[k] = @args[k] if @args.include?(k) }

        @defaults.each { |k, v| @args.key?(k) ? h[k] = @args[k] : h[k] = v }

        h
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
discourse_api-2.0.1 lib/discourse_api/api/params.rb
discourse_api-2.0.0 lib/discourse_api/api/params.rb