Class: TeamworkApi::API::Params

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

Overview

The useful stuff is here

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Params

Returns a new instance of Params.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
# File 'lib/teamwork_api/api/params.rb', line 12

def initialize(args)
  raise(ArgumentError, 'Required to be initialized with a Hash') unless
    args.is_a? Hash

  @args = args
  @required = []
  @optional = []
  @defaults = {}
end

Instance Method Details

#camelize(string) ⇒ Object



68
69
70
71
72
73
# File 'lib/teamwork_api/api/params.rb', line 68

def camelize(string)
  string = string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { $&.downcase }
  string.gsub(%r{(?:_|(\/))([a-z\d]*)}) {
    "#{Regexp.last_match(1)}#{Regexp.last_match(2).capitalize}"
  }.gsub('/', '::')
end

#caseify_keys(hash) ⇒ Object



58
59
60
61
62
63
64
65
66
# File 'lib/teamwork_api/api/params.rb', line 58

def caseify_keys(hash)
  caseified_hash = {}
  hash.each do |k, v|
    key = (k.match?(/-/) ? k.to_s : camelize(k.to_s))
    caseified_hash[key] = v
  end

  caseified_hash
end

#default(args) ⇒ Object



32
33
34
35
36
37
# File 'lib/teamwork_api/api/params.rb', line 32

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

#optional(*keys) ⇒ Object



27
28
29
30
# File 'lib/teamwork_api/api/params.rb', line 27

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

#required(*keys) ⇒ Object



22
23
24
25
# File 'lib/teamwork_api/api/params.rb', line 22

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

#to_hObject



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

def to_h
  h = {}

  @required.each do |k|
    h[k] = @args[k]
    raise(ArgumentError, "#{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|
    h[k] = (@args.key?(k) ? @args[k] : v)
  end

  caseify_keys(h)
end