Sha256: 0dc33bb5a1259a5c6a01986b8b28b188370a43145606d852b63274eea4a6e412

Contents?: true

Size: 1.01 KB

Versions: 6

Compression:

Stored size: 1.01 KB

Contents

module DiscourseApi
  module API
    def self.params(args)
      Params.new(args)
    end

    class Params
      def initialize(args)
        @args = args
        @required = []
        @optional = []
        @defaults = {}
      end

      def required(*keys)
        @required.concat(keys)
        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]
          raise ArgumentError.new("#{k} is required but not specified") unless h[k]
        end

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

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

        h

      end
    end

  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
discourse_api-0.4.4 lib/discourse_api/api/params.rb
discourse_api-0.4.3 lib/discourse_api/api/params.rb
discourse_api-0.4.2 lib/discourse_api/api/params.rb
discourse_api-0.4.1 lib/discourse_api/api/params.rb
discourse_api-0.4.0 lib/discourse_api/api/params.rb
discourse_api-0.3.6 lib/discourse_api/api/params.rb