module Frontline::Inflector
Public Instance Methods
inflections(locale = :en) { |instance| ... }
click to toggle source
Yields a singleton instance of Inflector::Inflections
so you can specify additional inflector rules. If passed an optional locale, rules for other languages can be specified. If not specified, defaults to :en
. Only rules for English are provided.
ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.uncountable 'rails' end
# File lib/frontline/inflect.rb, line 56 def inflections(locale = :en) if block_given? yield Inflections.instance(locale) else Inflections.instance(locale) end end
pluralize(word, locale = :en)
click to toggle source
Returns the plural form of the word in the string.
If passed an optional locale
parameter, the word will be pluralized using rules defined for that language. By default, this parameter is set to :en
.
'post'.pluralize # => "posts" 'octopus'.pluralize # => "octopi" 'sheep'.pluralize # => "sheep" 'words'.pluralize # => "words" 'CamelOctopus'.pluralize # => "CamelOctopi" 'ley'.pluralize(:es) # => "leyes"
# File lib/frontline/inflect.rb, line 134 def pluralize(word, locale = :en) apply_inflections(word, inflections(locale).plurals) end
singularize(word, locale = :en)
click to toggle source
The reverse of pluralize
, returns the singular form of a word in a string.
If passed an optional locale
parameter, the word will be pluralized using rules defined for that language. By default, this parameter is set to :en
.
'posts'.singularize # => "post" 'octopi'.singularize # => "octopus" 'sheep'.singularize # => "sheep" 'word'.singularize # => "word" 'CamelOctopi'.singularize # => "CamelOctopus" 'leyes'.singularize(:es) # => "ley"
# File lib/frontline/inflect.rb, line 151 def singularize(word, locale = :en) apply_inflections(word, inflections(locale).singulars) end
underscore(camel_cased_word)
click to toggle source
# File lib/frontline/inflect.rb, line 155 def underscore(camel_cased_word) word = camel_cased_word.to_s.dup word.gsub!('::', '/') word.gsub!(/(?:([A-Za-z\d])|^)((?=a)b)(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$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
Private Instance Methods
apply_inflections(word, rules)
click to toggle source
Applies inflection rules for singularize
and pluralize
.
apply_inflections('post', inflections.plurals) # => "posts" apply_inflections('posts', inflections.singulars) # => "post"
# File lib/frontline/inflect.rb, line 172 def apply_inflections(word, rules) result = word.to_s.dup if word.empty? || inflections.uncountables.include?(result.downcase[/\b\w+\Z/]) result else rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } result end end