Class: StringCases
- Inherits:
-
Object
- Object
- StringCases
- Defined in:
- lib/string-cases.rb
Class Method Summary collapse
- .camel_to_snake(str) ⇒ Object
- .constantize(str) ⇒ Object
- .hash_keys(hash, mode, args = {}) ⇒ Object
- .pluralize(str) ⇒ Object
- .singularize(str) ⇒ Object
- .snake_to_camel(str) ⇒ Object
- .stringify_keys(hash, args = {}) ⇒ Object
- .symbolize_keys(hash, args = {}) ⇒ Object
Class Method Details
.camel_to_snake(str) ⇒ Object
6 7 8 |
# File 'lib/string-cases.rb', line 6 def self.camel_to_snake(str) str.to_s.gsub(/(.)([A-Z])/, '\1_\2').downcase end |
.constantize(str) ⇒ Object
34 35 36 37 38 |
# File 'lib/string-cases.rb', line 34 def self.constantize(str) str.to_s.split("::").inject(Module) do |mod_path, mod_to_find| mod_path.const_get(mod_to_find) end end |
.hash_keys(hash, mode, args = {}) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/string-cases.rb', line 40 def self.hash_keys(hash, mode, args = {}) new_hash = {} hash.each do |key, value| case mode when :stringify key = key.to_s if key.is_a?(Symbol) when :symbolize key = key.to_sym if key.is_a?(String) else raise "Unknown mode: #{mode}" end value = StringCases.hash_keys(value, mode, args) if args[:recursive] && value.is_a?(Hash) new_hash[key] = value end new_hash end |
.pluralize(str) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/string-cases.rb', line 10 def self.pluralize(str) str = "#{str}" if str.match(/([^aeiouy]|qu)y$/i) str = str.gsub(/y\Z/, "ies") else str << "s" end str end |
.singularize(str) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/string-cases.rb', line 22 def self.singularize(str) str = "#{str}" if str.end_with?("ies") str = str.gsub(/ies\Z/, "y") else str = str.gsub(/s\Z/, "") end str end |
.snake_to_camel(str) ⇒ Object
2 3 4 |
# File 'lib/string-cases.rb', line 2 def self.snake_to_camel(str) str.to_s.split("_").map(&:capitalize).join("") end |
.stringify_keys(hash, args = {}) ⇒ Object
63 64 65 |
# File 'lib/string-cases.rb', line 63 def self.stringify_keys(hash, args = {}) StringCases.hash_keys(hash, :stringify, args) end |
.symbolize_keys(hash, args = {}) ⇒ Object
59 60 61 |
# File 'lib/string-cases.rb', line 59 def self.symbolize_keys(hash, args = {}) StringCases.hash_keys(hash, :symbolize, args) end |