Module: WebCrawler::Utility

Extended by:
Utility
Included in:
WebCrawler, Utility
Defined in:
lib/web_crawler/utility.rb

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"


19
20
21
22
23
24
25
# File 'lib/web_crawler/utility.rb', line 19

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

#dasherize(underscored_word) ⇒ Object

Replaces underscores with dashes in the string.

Example:

"puni_puni" # => "puni-puni"


53
54
55
# File 'lib/web_crawler/utility.rb', line 53

def dasherize(underscored_word)
  underscored_word.gsub(/_/, '-')
end

#demodulize(class_name_in_module) ⇒ Object

Removes the module part from the expression in the string.

Examples:

"ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
"Inflections".demodulize                                       # => "Inflections"


62
63
64
# File 'lib/web_crawler/utility.rb', line 62

def demodulize(class_name_in_module)
  class_name_in_module.to_s.gsub(/^.*::/, '')
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"


39
40
41
42
43
44
45
46
47
# File 'lib/web_crawler/utility.rb', line 39

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