module Stretchy::Utils::Methods

Public Instance Methods

coerce_id(id) click to toggle source

coerces ids to integers, unless they contain non-integers

# File lib/stretchy/utils.rb, line 43
def coerce_id(id)
  id =~ /^\d+$/ ? id.to_i : id
end
current_page(offset, limit) click to toggle source

must be shared between api & results

# File lib/stretchy/utils.rb, line 38
def current_page(offset, limit)
  ((offset + 1.0) / limit).ceil
end
dotify(hash, prefixes = []) click to toggle source
# File lib/stretchy/utils.rb, line 47
def dotify(hash, prefixes = [])
  hash.reduce({}) do |memo, kv|
    key, val    = kv
    subprefixes = (prefixes + [key])
    prefix      = subprefixes.join('.')
    if val.is_a? Hash
      memo.merge(dotify(val, subprefixes))
    else
      memo.merge(prefix => val)
    end
  end
end
extract_options!(params, list) click to toggle source

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

# File lib/stretchy/utils.rb, line 31
def extract_options!(params, list)
  output = Hash[list.map do |opt|
    [opt, params.delete(opt)]
  end].keep_if {|k,v| !is_empty?(v)}
end
is_empty?(arg = nil) click to toggle source

detects empty string, empty array, empty hash, nil

# File lib/stretchy/utils.rb, line 6
def is_empty?(arg = nil)
  return true if arg.nil?
  if arg.respond_to?(:collector)
    !arg.collector.any?
  elsif arg.respond_to?(:any?)
    !arg.any? {|a| !is_empty?(a) }
  elsif arg.respond_to?(:empty?)
    arg.empty?
  else
    !arg
  end
end
nestify(hash, prefixes = []) click to toggle source
# File lib/stretchy/utils.rb, line 60
def nestify(hash, prefixes = [])
  hash.reduce({}) do |memo, kv|
    key, val = kv
    subprefixes = (prefixes + [key])
    prefix = subprefixes.join('.')
    if val.is_a? Hash
      memo.merge(prefix => nestify(val, subprefixes))
    else
      memo.merge(prefix => val)
    end
  end
end
require_params!(method, params, *fields) click to toggle source

raises error if required parameters are missing

# File lib/stretchy/utils.rb, line 20
def require_params!(method, params, *fields)
  raise Errors::InvalidParamsError.new(
    "#{method} requires at least #{fields.join(' and ')} params, but " +
    "found: #{params}"
  ) if fields.any? {|f| is_empty? params[f] }

  true
end