Module: CoreExtensions::String

Defined in:
lib/core_ext.rb,
lib/core_ext.rb

Overview

BOOLEAN #########################################################################################

Constant Summary collapse

SPACE_CHAR_CLASS =
'\p{Space}\u180e\u200b\u200c\u200d\u2060\ufeff'.freeze
LSTRIP_SPACE_REGEX =
%r{\A[#{SPACE_CHAR_CLASS}]+}.freeze
RSTRIP_SPACE_REGEX =
%r{[#{SPACE_CHAR_CLASS}]+\z}.freeze

Instance Method Summary collapse

Instance Method Details

#force_utf8Object



38
39
40
41
42
43
44
# File 'lib/core_ext.rb', line 38

def force_utf8
  if (encoding == Encoding::UTF_8) && valid_encoding?
    self
  else
    encode('utf-8', invalid: :replace, undef: :replace)
  end
end

#lstripObject



13
14
15
# File 'lib/core_ext.rb', line 13

def lstrip
  (encoding == Encoding::UTF_8) ? sub(LSTRIP_SPACE_REGEX, '') : super
end

#possessiveObject



32
33
34
35
36
# File 'lib/core_ext.rb', line 32

def possessive
  str = self + "'"
  str += 's' unless %r{(s|se|z|ze|ce|x|xe)$}i.match(self)
  str
end

#rstripObject



17
18
19
# File 'lib/core_ext.rb', line 17

def rstrip
  (encoding == Encoding::UTF_8) ? sub(RSTRIP_SPACE_REGEX, '') : super
end

#stripObject



21
22
23
24
25
26
27
28
29
30
# File 'lib/core_ext.rb', line 21

def strip
  if encoding == Encoding::UTF_8
    dup.tap do |str|
      str.sub!(LSTRIP_SPACE_REGEX, '')
      str.sub!(RSTRIP_SPACE_REGEX, '')
    end
  else
    super
  end
end

#to_bool(default = nil) ⇒ Object



176
177
178
179
180
# File 'lib/core_ext.rb', line 176

def to_bool(default = nil)
  return true  if %w(true  1 yes on  t).include?(self.downcase.strip)
  return false if %w(false 0  no off f).include?(self.downcase.strip)
  default
end

#to_hexObject



46
47
48
# File 'lib/core_ext.rb', line 46

def to_hex
  self.b.unpack('H*').first
end