module Ruhoh::StringFormat
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.
Public Class Methods
clean_slug(string)
click to toggle source
Public interface for building ‘clean slugs’ Redefine this method to implement custom slug generation.
# File lib/ruhoh/string_format.rb, line 14 def self.clean_slug(string) hyphenate(string) end
clean_slug_and_escape(string)
click to toggle source
# File lib/ruhoh/string_format.rb, line 18 def self.clean_slug_and_escape(string) CGI::escape(clean_slug(string)) end
hyphenate(string)
click to toggle source
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
# File lib/ruhoh/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)
click to toggle source
Convert CamelCase to snake_case
Thanks ActiveSupport: stackoverflow.com/a/1509939/101940
# File lib/ruhoh/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)
click to toggle source
TODO: Probably use ActiveSupport for this stuff Ex: my-post-title ===> My Post Title
# File lib/ruhoh/string_format.rb, line 35 def self.titleize(string) string.gsub(/[^\p{Word}+]/u, ' ').gsub(/\b\w/){ $&.upcase } end