Class: Replay::Inflector
- Inherits:
-
Object
- Object
- Replay::Inflector
- Defined in:
- lib/replay/inflector.rb
Overview
This class substantially copied from ActiveSupport, licensed under MIT Their version is generally better, so use that unless you’ve got a good reason not to do so. also, i’ve changed certain aspects of behavior.
Class Method Summary collapse
-
.camelize(term, uppercase_first_letter = false) ⇒ Object
By default,
camelizeconverts strings to UpperCamelCase. - .constantize(class_name) ⇒ Object
-
.underscore(camel_cased_word) ⇒ Object
Makes an underscored, lowercase form from the expression in the string.
Class Method Details
.camelize(term, uppercase_first_letter = false) ⇒ Object
By default, camelize converts strings to UpperCamelCase. If the argument to camelize is set to :lower then camelize produces lowerCamelCase.
camelize will also convert ‘/’ to ‘::’ which is useful for converting paths to namespaces.
'active_model'.camelize # => "ActiveModel"
'active_model'.camelize(:lower) # => "activeModel"
'active_model/errors'.camelize # => "ActiveModel::Errors"
'active_model/errors'.camelize(:lower) # => "activeModel::Errors"
As a rule of thumb you can think of camelize as the inverse of underscore, though there are cases where that does not hold:
'SSLError'.underscore.camelize # => "SslError"
22 23 24 25 26 27 28 29 |
# File 'lib/replay/inflector.rb', line 22 def self.camelize(term, uppercase_first_letter = false) string = term.to_s string = string.sub(/^[A-Z_]/) { $&.downcase } string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{$2.capitalize}" } string.gsub!('/', '::') string.gsub!('.', '::') string end |
.constantize(class_name) ⇒ Object
52 53 54 |
# File 'lib/replay/inflector.rb', line 52 def self.constantize(class_name) class_name.to_s.split("::").inject(Kernel){|parent, mod| parent.const_get(mod)} end |
.underscore(camel_cased_word) ⇒ Object
Makes an underscored, lowercase form from the expression in the string.
Changes ‘::’ to ‘/’ to convert namespaces to paths.
'ActiveModel'.underscore # => "active_model"
'ActiveModel::Errors'.underscore # => "active_model/errors"
As a rule of thumb you can think of underscore as the inverse of camelize, though there are cases where that does not hold:
'SSLError'.underscore.camelize # => "SslError"
41 42 43 44 45 46 47 48 49 50 |
# File 'lib/replay/inflector.rb', line 41 def self.underscore(camel_cased_word) return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/ word = camel_cased_word.to_s.gsub('::', '.') word.gsub!(/(?:([A-Za-z\d])^)(?=\b|[^a-z])/) { "#{$1}#{$2 && '_'}#{$2.downcase}" } word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') word.tr!("-", "_") word.downcase! word end |