Module: SmartEnum::Utilities

Defined in:
lib/smart_enum/utilities.rb

Class Method Summary collapse

Class Method Details

.camelize(string) ⇒ Object

Convert snake case string to camelcase string. Adapted from github.com/jeremyevans/sequel/blob/5.10.0/lib/sequel/model/inflections.rb#L103



36
37
38
39
40
# File 'lib/smart_enum/utilities.rb', line 36

def self.camelize(string)
  string.to_s
    .gsub(/\/(.?)/){|x| "::#{x[-1..-1].upcase unless x == '/'}"}
    .gsub(/(^|_)(.)/){|x| x[-1..-1].upcase}
end

.classify(string) ⇒ Object



30
31
32
# File 'lib/smart_enum/utilities.rb', line 30

def self.classify(string)
  singularize(camelize(string))
end

.constantize(string) ⇒ Object



14
15
16
# File 'lib/smart_enum/utilities.rb', line 14

def self.constantize(string)
  Object.const_get(string)
end

.foreign_key(string) ⇒ Object



18
19
20
# File 'lib/smart_enum/utilities.rb', line 18

def self.foreign_key(string)
  singularize(tableize(string)) + "_id"
end

.singularize(string) ⇒ Object



22
23
24
# File 'lib/smart_enum/utilities.rb', line 22

def self.singularize(string)
  string.to_s.chomp("s")
end

.symbolize_hash_keys(original_hash) ⇒ Object



5
6
7
8
9
10
11
12
# File 'lib/smart_enum/utilities.rb', line 5

def self.symbolize_hash_keys(original_hash)
  return original_hash if original_hash.each_key.all?{|key| Symbol === key }
  symbolized_hash = {}
  original_hash.each_key do |key|
    symbolized_hash[key.to_sym] = original_hash[key]
  end
  symbolized_hash
end

.tableize(string) ⇒ Object



26
27
28
# File 'lib/smart_enum/utilities.rb', line 26

def self.tableize(string)
  underscore(string) + "s"
end

.underscore(string) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/smart_enum/utilities.rb', line 44

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