Module: Blendris::Utils

Included in:
RedisAccessor
Defined in:
lib/blendris/utils.rb

Overview

This module provides a few utility methods that are used throughout Blendris.

Instance Method Summary collapse

Instance Method Details

#blank(obj) ⇒ Object

Tests if the given object is blank.



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

def blank(obj)
  return true if obj.nil?
  return obj.strip.empty? if obj.kind_of? String
  return obj.empty? if obj.respond_to? :empty?
  return false
end

#camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) ⇒ Object

Method lifted from Rails.



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

def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
  if first_letter_in_uppercase
    lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase }
  else
    lower_case_and_underscored_word.first + camelize(lower_case_and_underscored_word)[1..-1]
  end
end

#constantize(camel_cased_word) ⇒ Object

Method lifted from Rails.



8
9
10
11
12
13
14
15
16
# File 'lib/blendris/utils.rb', line 8

def constantize(camel_cased_word)
  return if blank(camel_cased_word)

  unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
    raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"
  end

  Object.module_eval("::#{$1}", __FILE__, __LINE__)
end

#pairify(*arr) ⇒ Object

Take an array and turn it into a list of pairs.



42
43
44
45
46
47
48
49
50
# File 'lib/blendris/utils.rb', line 42

def pairify(*arr)
  arr = arr.flatten

  if arr.length == 1 && arr.first.kind_of?(Hash)
    arr.first.map { |k, v| [ k, v ] }
  else
    (0 ... arr.length/2).map { |i| [ arr[2*i], arr[2*i + 1] ] }
  end
end

#sanitize_key(key) ⇒ Object

Redis keys cannot contain spaces, carriage returns, or newlines. We do not want colons at the start or end of keys.



37
38
39
# File 'lib/blendris/utils.rb', line 37

def sanitize_key(key)
  key.to_s.gsub(/[\r\n\s]/, "_").gsub(/^:+|:+$/, "")
end