Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/string.rb

Constant Summary collapse

MAP_WORDS =
{
 "ping_api"=>"PingAPI", 
 "im_client"=>"IMClient", 
 "ogrn"=>"OGRN", 
 "phrase_id"=>"PhraseID",
 "campaign_id" => "CampaignID",
 "campaign_ids" => "CampaignIDS"
}

Instance Method Summary collapse

Instance Method Details

#camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) ⇒ 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.

Examples:

"active_record".camelize                # => "ActiveRecord"
"active_record".camelize(:lower)        # => "activeRecord"
"active_record/errors".camelize         # => "ActiveRecord::Errors"
"active_record/errors".camelize(:lower) # => "activeRecord::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"


41
42
43
44
45
46
47
# File 'lib/string.rb', line 41

def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
  if first_letter_in_uppercase
    lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
  else
    lower_case_and_underscored_word.to_s[0].chr.downcase + camelize(lower_case_and_underscored_word)[1..-1]
  end
end

#find_exeption_wordsObject



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

def find_exeption_words
  MAP_WORDS[self]
end

#to_camelcaseObject



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

def to_camelcase
  MAP_WORDS[self] || camelize(self)
end

#to_underscoreObject



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

def to_underscore
  underscore(self)
end

#underscore(camel_cased_word) ⇒ Object

Makes an underscored, lowercase form from the expression in the string.

Changes ‘::’ to ‘/’ to convert namespaces to paths.

Examples:

"ActiveRecord".underscore         # => "active_record"
"ActiveRecord::Errors".underscore # => active_record/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"


61
62
63
64
65
66
67
68
69
# File 'lib/string.rb', line 61

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