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
34
35
# File 'lib/discourse_api/api/params.rb', line 30

def default(args)
  args.each do |k, v|
    @defaults[k] = v
  end
  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



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/discourse_api/api/params.rb', line 37

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