Sha256: f164cfa75cfef61afcd5c7d3db448261baef37ce94827ddb3693887ae73f75b6

Contents?: true

Size: 1021 Bytes

Versions: 35

Compression:

Stored size: 1021 Bytes

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

        @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

35 entries across 35 versions & 1 rubygems

Version Path
discourse_api-0.34.0 lib/discourse_api/api/params.rb
discourse_api-0.33.0 lib/discourse_api/api/params.rb
discourse_api-0.32.0 lib/discourse_api/api/params.rb
discourse_api-0.31.0 lib/discourse_api/api/params.rb
discourse_api-0.30.0 lib/discourse_api/api/params.rb
discourse_api-0.29.0 lib/discourse_api/api/params.rb
discourse_api-0.28.1 lib/discourse_api/api/params.rb
discourse_api-0.28.0 lib/discourse_api/api/params.rb
discourse_api-0.27.0 lib/discourse_api/api/params.rb
discourse_api-0.26.0 lib/discourse_api/api/params.rb
discourse_api-0.25.0 lib/discourse_api/api/params.rb
discourse_api-0.24.0 lib/discourse_api/api/params.rb
discourse_api-0.23.1 lib/discourse_api/api/params.rb
discourse_api-0.23.0 lib/discourse_api/api/params.rb
discourse_api-0.22.0 lib/discourse_api/api/params.rb
discourse_api-0.20.1 lib/discourse_api/api/params.rb
discourse_api-0.20.0 lib/discourse_api/api/params.rb
discourse_api-0.19.0 lib/discourse_api/api/params.rb
discourse_api-0.18.0 lib/discourse_api/api/params.rb
discourse_api-0.17.0 lib/discourse_api/api/params.rb