Module: Stretchy::Utils::Methods

Included in:
API, Results, Stretchy::Utils
Defined in:
lib/stretchy/utils.rb

Instance Method Summary collapse

Instance Method Details

#coerce_id(id) ⇒ Object

coerces ids to integers, unless they contain non-integers



41
42
43
# File 'lib/stretchy/utils.rb', line 41

def coerce_id(id)
  id =~ /\d+/ ? id.to_i : id
end

#current_page(offset, limit) ⇒ Object

must be shared between api & results



36
37
38
# File 'lib/stretchy/utils.rb', line 36

def current_page(offset, limit)
  ((offset + 1.0) / limit).ceil
end

#extract_options!(params, list) ⇒ Object

generates a hash of specified options, removing them from the original hash



29
30
31
32
33
# File 'lib/stretchy/utils.rb', line 29

def extract_options!(params, list)
  boost_params = Hash[list.map do |opt|
    [opt, params.delete(opt)]
  end].keep_if {|k,v| !is_empty?(v)}
end

#is_empty?(arg = nil) ⇒ Boolean

detects empty string, empty array, empty hash, nil

Returns:

  • (Boolean)


6
7
8
9
10
11
12
13
14
15
# File 'lib/stretchy/utils.rb', line 6

def is_empty?(arg = nil)
  return true if arg.nil?
  if arg.respond_to?(:any?)
    !arg.any? {|a| !is_empty?(a) }
  elsif arg.respond_to?(:empty?)
    arg.empty?
  else
    !arg
  end
end

#require_params!(method, params, *fields) ⇒ Object

raises error if required parameters are missing

Raises:

  • (Errors::InvalidParamsError)


18
19
20
21
22
23
24
25
# File 'lib/stretchy/utils.rb', line 18

def require_params!(method, params, *fields)
  raise Errors::InvalidParamsError.new(
    "#{method} requires at least #{fields.join(' and ')} params",
    "params found: #{params}"
  ) if fields.any? {|f| is_empty? params[f] }

  true
end