Module: Stretchy::Utils::Methods
- Included in:
- API, Results, Stretchy::Utils
- Defined in:
- lib/stretchy/utils.rb
Instance Method Summary collapse
-
#coerce_id(id) ⇒ Object
coerces ids to integers, unless they contain non-integers.
-
#current_page(offset, limit) ⇒ Object
must be shared between api & results.
- #dotify(hash, prefixes = []) ⇒ Object
-
#extract_options!(params, list) ⇒ Object
generates a hash of specified options, removing them from the original hash.
-
#is_empty?(arg = nil) ⇒ Boolean
detects empty string, empty array, empty hash, nil.
- #nestify(hash, prefixes = []) ⇒ Object
-
#require_params!(method, params, *fields) ⇒ Object
raises error if required parameters are missing.
Instance Method Details
#coerce_id(id) ⇒ Object
coerces ids to integers, unless they contain non-integers
43 44 45 |
# File 'lib/stretchy/utils.rb', line 43 def coerce_id(id) id =~ /^\d+$/ ? id.to_i : id end |
#current_page(offset, limit) ⇒ Object
must be shared between api & results
38 39 40 |
# File 'lib/stretchy/utils.rb', line 38 def current_page(offset, limit) ((offset + 1.0) / limit).ceil end |
#dotify(hash, prefixes = []) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 |
# 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) ⇒ Object
generates a hash of specified options, removing them from the original hash
31 32 33 34 35 |
# File 'lib/stretchy/utils.rb', line 31 def (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) ⇒ Boolean
detects empty string, empty array, empty hash, nil
6 7 8 9 10 11 12 13 14 15 16 17 |
# 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 = []) ⇒ Object
60 61 62 63 64 65 66 67 68 69 70 71 |
# 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) ⇒ Object
raises error if required parameters are missing
20 21 22 23 24 25 26 27 |
# 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 |