Sha256: f104e6cb73b00df364e0b8213e8ca37dcb1a6cfbbc329a572a85b2b59e0e0e46

Contents?: true

Size: 1.08 KB

Versions: 18

Compression:

Stored size: 1.08 KB

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 do |k, v|
          @defaults[k] = v
        end
        self
      end

      def to_h
        h = {}

        @required.each do |k|
          h[k] = @args[k]
        end

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

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

        h

      end
    end

  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
discourse_api-1.1.0 lib/discourse_api/api/params.rb
discourse_api-1.0.0 lib/discourse_api/api/params.rb
discourse_api-0.48.1 lib/discourse_api/api/params.rb
discourse_api-0.48.0 lib/discourse_api/api/params.rb
discourse_api-0.47.0 lib/discourse_api/api/params.rb
discourse_api-0.46.0 lib/discourse_api/api/params.rb
discourse_api-0.45.1 lib/discourse_api/api/params.rb
discourse_api-0.45.0 lib/discourse_api/api/params.rb
discourse_api-0.44.0 lib/discourse_api/api/params.rb
discourse_api-0.43.1 lib/discourse_api/api/params.rb
discourse_api-0.43.0 lib/discourse_api/api/params.rb
discourse_api-0.42.0 lib/discourse_api/api/params.rb
discourse_api-0.41.0 lib/discourse_api/api/params.rb
discourse_api-0.40.0 lib/discourse_api/api/params.rb
discourse_api-0.39.3 lib/discourse_api/api/params.rb
discourse_api-0.39.2 lib/discourse_api/api/params.rb
discourse_api-0.39.1 lib/discourse_api/api/params.rb
discourse_api-0.39.0 lib/discourse_api/api/params.rb