Sha256: af2efa5778e68bc16d63f870d45266f65f744b0e9059c44549e6a854bfc3836a

Contents?: true

Size: 1.1 KB

Versions: 4

Compression:

Stored size: 1.1 KB

Contents

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)
        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

4 entries across 4 versions & 1 rubygems

Version Path
discourse_api-0.6.1 lib/discourse_api/api/params.rb
discourse_api-0.6.0 lib/discourse_api/api/params.rb
discourse_api-0.5.1 lib/discourse_api/api/params.rb
discourse_api-0.5.0 lib/discourse_api/api/params.rb