Class: DiscourseApi::API::Params

Inherits:
Object
  • Object
show all
Defined in:
lib/discourse_api/api/params.rb

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Params

Returns a new instance of Params.

Raises:

  • (ArgumentError)


9
10
11
12
13
14
15
# File 'lib/discourse_api/api/params.rb', line 9

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

Instance Method Details

#default(args) ⇒ Object



30
31
32
33
# File 'lib/discourse_api/api/params.rb', line 30

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

#optional(*keys) ⇒ Object



25
26
27
28
# File 'lib/discourse_api/api/params.rb', line 25

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

#required(*keys) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/discourse_api/api/params.rb', line 17

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

#to_hObject



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/discourse_api/api/params.rb', line 35

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