Created
April 12, 2012 23:10
-
-
Save mahemoff/2371687 to your computer and use it in GitHub Desktop.
acronym support in rails 3.1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# "borrowed" from https://github.com/rails/rails/tree/3-2-stable/railties/lib/rails/generators/rails/app/templates/config/initializers | |
module Irregularities | |
attr_accessor :acronyms | |
def acronym(word) | |
@acronyms[word.downcase] = word | |
@acronym_regex = /#{@acronyms.values.join("|")}/ | |
end | |
def underscore(camel_cased_word) | |
word = camel_cased_word.to_s.dup | |
word.gsub!(/::/, '/') | |
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\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 | |
def camelize(term, uppercase_first_letter = true) | |
string = term.to_s | |
if uppercase_first_letter | |
string = string.sub(/^[a-z\d]*/) { inflections.acronyms[$&] || $&.capitalize } | |
else | |
string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase } | |
end | |
string.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }.gsub('/', '::') | |
end | |
def humanize(lower_case_and_underscored_word) | |
result = lower_case_and_underscored_word.to_s.dup | |
inflections.humans.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } | |
result.gsub!(/_id$/, "") | |
result.gsub!(/_/, ' ') | |
result.gsub(/([a-z\d]*)/i) { |match| | |
"#{inflections.acronyms[match] || match.downcase}" | |
}.gsub(/^\w/) { $&.upcase } | |
end | |
def underscore(camel_cased_word) | |
word = camel_cased_word.to_s.dup | |
word.gsub!(/::/, '/') | |
word.gsub!(/(?:([A-Za-z\d])|^)(#{inflections.acronym_regex})(?=\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 | |
end | |
ActiveSupport::Inflector.inflections do |inflect| | |
inflect.extend(Irregularities) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment