Module: Silly::StringFormat
- Defined in:
- lib/silly/string_format.rb
Overview
StringFormat is meant to expose the common (public) interface for where strings (namely URLS) are formatted. Users are encouraged to reimplement these methods via plugins to enable custom-defined slug generation logic based on their tastes.
TODO:
- Natively support the most popular slug formats.
- Better support for Internationalization.
Class Method Summary collapse
-
.clean_slug(string) ⇒ Object
Public interface for building ‘clean slugs’ Redefine this method to implement custom slug generation.
- .clean_slug_and_escape(string) ⇒ Object
-
.hyphenate(string) ⇒ Object
Simple url slug normalization.
-
.snake_case(string) ⇒ Object
Convert CamelCase to snake_case Thanks ActiveSupport: stackoverflow.com/a/1509939/101940.
-
.titleize(string) ⇒ Object
TODO: Probably use ActiveSupport for this stuff Ex: my-post-title ===> My Post Title.
Class Method Details
.clean_slug(string) ⇒ Object
Public interface for building ‘clean slugs’ Redefine this method to implement custom slug generation.
14 15 16 |
# File 'lib/silly/string_format.rb', line 14 def self.clean_slug(string) hyphenate(string) end |
.clean_slug_and_escape(string) ⇒ Object
18 19 20 |
# File 'lib/silly/string_format.rb', line 18 def self.clean_slug_and_escape(string) CGI::escape(clean_slug(string)) end |
.hyphenate(string) ⇒ Object
Simple url slug normalization. Converts all non word characters into hyphens. This may not be what you want so feel free to overwite the public method in place of another formatter.
Ex: My Post Title ===> my-post-title
28 29 30 31 |
# File 'lib/silly/string_format.rb', line 28 def self.hyphenate(string) string = string.to_s.downcase.strip.gsub(/[^\p{Word}+]/u, '-') string.gsub(/^\-+/, '').gsub(/\-+$/, '').gsub(/\-+/, '-') end |
.snake_case(string) ⇒ Object
Convert CamelCase to snake_case Thanks ActiveSupport: stackoverflow.com/a/1509939/101940
41 42 43 44 45 46 47 48 49 |
# File 'lib/silly/string_format.rb', line 41 def self.snake_case(string) string. to_s. gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end |
.titleize(string) ⇒ Object
TODO: Probably use ActiveSupport for this stuff Ex: my-post-title ===> My Post Title
35 36 37 |
# File 'lib/silly/string_format.rb', line 35 def self.titleize(string) string.gsub(/[^\p{Word}+]/u, ' ').gsub(/\b\w/){ $&.upcase } end |