Module: SugarUtils

Defined in:
lib/sugar_utils.rb,
lib/sugar_utils/file.rb,
lib/sugar_utils/version.rb,
lib/sugar_utils/file/write_options.rb

Defined Under Namespace

Modules: File

Constant Summary collapse

VERSION =
'0.6.0'.freeze

Class Method Summary collapse

Class Method Details

.ensure_boolean(value) ⇒ Boolean


11
12
13
14
15
# File 'lib/sugar_utils.rb', line 11

def self.ensure_boolean(value)
  return false if value.respond_to?(:to_s) && value.to_s.casecmp('false').zero?

  value ? true : false
end

.ensure_integer(value) ⇒ Integer

Raises:

  • (ArgumentError)

    if the value is a string which cannot be converted

  • (TypeError)

    if value is type which cannot be converted


23
24
25
26
27
28
# File 'lib/sugar_utils.rb', line 23

def self.ensure_integer(value)
  return value      if value.is_a?(Integer)
  return value.to_i if value.is_a?(Float)

  Float(value).to_i
end

.scrub_encoding(data) ⇒ String .scrub_encoding(data, replacement_character) ⇒ String

Overloads:

  • .scrub_encoding(data) ⇒ String

    Scrub the string's encoding, and replace any bad characters with ''.

  • .scrub_encoding(data, replacement_character) ⇒ String

    Scrub the string's encoding, and replace any bad characters with the specified character.


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/sugar_utils.rb', line 40

def self.scrub_encoding(data, replacement_character = nil)
  replacement_character = '' unless replacement_character.is_a?(String)

  # If the Ruby version being used supports String#scrub, then just use it.
  return data.scrub(replacement_character) if data.respond_to?(:scrub)

  # Otherwise, fall back to String#encode.
  data.encode(
    data.encoding,
    'binary',
    invalid: :replace,
    undef:   :replace, # rubocop:disable Layout/AlignHash
    replace: replacement_character
  )
end