Module: Lazier::String

Extended by:
ActiveSupport::Concern
Defined in:
lib/lazier/string.rb

Overview

Extensions for the String class.

Instance Method Summary collapse

Instance Method Details

#ensure_url_with_scheme(protocol = "http", secure: false) ⇒ Object

Makes sure the string starts with the scheme for the specified protocol.



24
25
26
27
# File 'lib/lazier/string.rb', line 24

def ensure_url_with_scheme(protocol = "http", secure: false)
  schema = protocol + (secure ? "s" : "")
  self !~ /^(#{protocol}(s?):\/\/)/ ? "#{schema}://#{self}" : self
end

#ensure_valid_utf8(replacement = "") ⇒ String

Makes sure the string only contains valid UTF-8 sequences.



15
16
17
18
# File 'lib/lazier/string.rb', line 15

def ensure_valid_utf8(replacement = "")
  # This odd line is because if need to specify a different encoding (without losing infos) to replace invalid bytes and then we go back to utf-8
  encode("utf-16", invalid: :replace, undef: :replace, replace: replacement).encode("utf-8")
end

#remove_accentsObject

Removes accents from the string, normalizing to the normal letter.

"èòàù".remove_accents
# => "eoau"


60
61
62
# File 'lib/lazier/string.rb', line 60

def remove_accents
  ::I18n.transliterate(self)
end

#tokenize(no_blanks: true, strip: true, no_duplicates: false, pattern: /\s*,\s*/, presence_method: :present?) ⇒ Array

Splits a string containing tokens using a specified pattern and applying some sanitizations.



44
45
46
47
48
49
50
# File 'lib/lazier/string.rb', line 44

def tokenize(no_blanks: true, strip: true, no_duplicates: false, pattern: /\s*,\s*/, presence_method: :present?)
  rv = split(pattern)
  rv.map!(&:strip) if strip
  rv.select!(&presence_method) if no_blanks
  rv.uniq! if no_duplicates
  rv
end

#valueString

Returns the string itself for use in form helpers.



32
33
34
# File 'lib/lazier/string.rb', line 32

def value
  self
end