Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/string.rb
Overview
Provides support methods for string manipulation
Instance Method Summary collapse
-
#camelcase(first_letter_capitalized = true) ⇒ Object
Converts dashes, underscores, and spaces to camelcase.
-
#demodulize ⇒ Object
Removes module and class prefixes.
-
#module_path ⇒ Object
Converts the string into a conventional path.
-
#module_split ⇒ Object
Splits the string into module and class components.
-
#underscore(force_lower_case = true) ⇒ Object
Converts dashes, spaces, and capitals to underscore separators.
Instance Method Details
#camelcase(first_letter_capitalized = true) ⇒ Object
Converts dashes, underscores, and spaces to camelcase
“foo_bar_baz”.camelcase => “FooBarBaz” “FooBarBaz”.camelcase(false) => “fooBarBaz”
8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/string.rb', line 8 def camelcase(first_letter_capitalized = true) # Convert separators camelcase = gsub(/[ _-]([^ _-])/) do |match| $1.upcase end # Convert first letter if first_letter_capitalized camelcase[0..0].upcase + camelcase[1..-1] else camelcase[0..0].downcase + camelcase[1..-1] end end |
#demodulize ⇒ Object
Removes module and class prefixes
“Foo::Bar::Baz”.demodulize => “Baz”
25 26 27 |
# File 'lib/string.rb', line 25 def demodulize self[/([^:]+)$/] end |
#module_path ⇒ Object
Converts the string into a conventional path.
37 38 39 |
# File 'lib/string.rb', line 37 def module_path File.join(module_split.map {|e| e.underscore }) end |
#module_split ⇒ Object
Splits the string into module and class components
“Foo::Bar::Baz”.module_split => [“Foo”, “Bar”, “Baz”]
32 33 34 |
# File 'lib/string.rb', line 32 def module_split self.split /::/ end |
#underscore(force_lower_case = true) ⇒ Object
Converts dashes, spaces, and capitals to underscore separators.
“FooBar-Baz Whee”.underscore => ‘foo_bar_baz_whee’
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/string.rb', line 44 def underscore(force_lower_case = true) # Convert separators underscore = gsub(/[ -]/, '_') # Convert capitals underscore.gsub!(/(.)([A-Z])/) do |match| $1 + '_' + $2 end # Drop double underscores underscore.gsub!(/_+/, '_') if force_lower_case underscore.downcase else underscore end end |