Class: Bodhi::Support

Inherits:
Object
  • Object
show all
Defined in:
lib/bodhi-slam/support.rb

Class Method Summary collapse

Class Method Details

.camelize(string) ⇒ Object



14
15
16
# File 'lib/bodhi-slam/support.rb', line 14

def self.camelize(string)
  underscore(string).split('_').collect(&:capitalize).join
end

.coerce(value, options) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/bodhi-slam/support.rb', line 31

def self.coerce(value, options)
  # nothing to coerce if the value is nil
  return value if value.nil?

  options = symbolize_keys(options)
  case options[:type].to_s
  when "String"
    if options[:multi] == true
      value.map(&:to_s)
    else
      value.to_s
    end
  when "Real"
    if options[:multi] == true
      value.map(&:to_f)
    else
      value.to_f
    end
  when "Integer"
    if options[:multi] == true
      value.map(&:to_i)
    else
      value.to_i
    end
  when "DateTime"
    if options[:multi] == true
      value.map{|item| Time.parse(item.to_s) }
    else
      Time.parse(value.to_s)
    end
  else
    if Object.const_defined?(options[:type].to_s) && Object.const_get(options[:type].to_s).ancestors.include?(Bodhi::Properties)
      klass = Object.const_get(options[:type].to_s)
      if options[:multi] == true
        value.map do |item|
          if item.respond_to?(:attributes)
            klass.new(item.attributes)
          else
            klass.new(item)
          end
        end
      else
        if value.respond_to?(:attributes)
          klass.new(value.attributes)
        else
          klass.new(value)
        end
      end
    else
      value
    end
  end
end

.reverse_camelize(string) ⇒ Object



18
19
20
21
# File 'lib/bodhi-slam/support.rb', line 18

def self.reverse_camelize(string)
  result = underscore(string).split('_').collect(&:capitalize).join
  uncapitalize(result)
end

.symbolize_keys(hash) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/bodhi-slam/support.rb', line 23

def self.symbolize_keys(hash)
  hash.reduce({}) do |memo, (k, v)|
    value = v.is_a?(Hash) ? symbolize_keys(v) : v
    value = value.is_a?(Array) && value.first.is_a?(Hash) ? value.map{|item| symbolize_keys(item) } : value
    memo.merge({ k.to_sym => value })
  end
end

.uncapitalize(string) ⇒ Object



10
11
12
# File 'lib/bodhi-slam/support.rb', line 10

def self.uncapitalize(string)
  string[0, 1].downcase + string[1..-1]
end

.underscore(string) ⇒ Object



3
4
5
6
7
8
# File 'lib/bodhi-slam/support.rb', line 3

def self.underscore(string)
  string.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
  gsub(/([a-z\d])([A-Z])/,'\1_\2').
  tr("-", "_").
  downcase
end