Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/younker-string-extensions.rb
Overview
Monkey-patching String
Instance Method Summary collapse
- #make_url_friendly ⇒ Object
- #pluralize_if(boolean) ⇒ Object
- #strip_html ⇒ Object
-
#truncate(length = 100, truncate_string = "...") ⇒ Object
Stepping all over the native truncate().
Instance Method Details
#make_url_friendly ⇒ Object
4 5 6 7 8 9 10 11 |
# File 'lib/younker-string-extensions.rb', line 4 def make_url_friendly # 1. Downcase string # 2. Remove apostrophes so isn't changes to isnt # 3. Replace any non-letter or non-number character with a space # 4. Remove spaces from beginning and end of string # 5. Replace groups of spaces with single hyphen self.downcase.gsub(/'/, '').gsub(/[^A-Za-z0-9]+/, ' ').strip.gsub(/\ +/, '-') end |
#pluralize_if(boolean) ⇒ Object
30 31 32 |
# File 'lib/younker-string-extensions.rb', line 30 def pluralize_if(boolean) boolean ? self.pluralize : self end |
#strip_html ⇒ Object
26 27 28 |
# File 'lib/younker-string-extensions.rb', line 26 def strip_html self.gsub(%r{</?[^>]+?>}, '') end |
#truncate(length = 100, truncate_string = "...") ⇒ Object
Stepping all over the native truncate()
14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/younker-string-extensions.rb', line 14 def truncate(length = 100, truncate_string = "...") # First regex truncates to the length, plus the rest of that word, if any. # Second regex removes any trailing whitespace or punctuation (except ;). # Unlike the regular truncate method, this avoids the problem with cutting # in the middle of an entity ex.: truncate("this & that",9) => "this &am..." # though it will not be the exact length. return if self.blank? l = length - truncate_string.length self.length > length ? self[/\A.{#{l}}\w*\;?/m][/.*[\w\;]/m] + truncate_string : self end |