Class: ConvenientService::Utils::String::Truncate

Inherits:
Support::Command show all
Defined in:
lib/convenient_service/utils/string/truncate.rb

Overview

Examples:

ConvenientService::Utils::String.truncate("hello", -1)                 # => ""
ConvenientService::Utils::String.truncate("hello", 0)                  # => ""
ConvenientService::Utils::String.truncate("hello", 1)                  # => "."
ConvenientService::Utils::String.truncate("hello", 2)                  # => ".."
ConvenientService::Utils::String.truncate("hello", 3)                  # => "..."
ConvenientService::Utils::String.truncate("hello", 4)                  # => "h..."
ConvenientService::Utils::String.truncate("hello", 4, omission: "--")  # => "he--"
ConvenientService::Utils::String.truncate("hello", 5)                  # => "hello"
ConvenientService::Utils::String.truncate("hello", 6)                  # => "hello"
ConvenientService::Utils::String.truncate("hello", 7)                  # => "hello"

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Support::Command

[], call

Constructor Details

#initialize(string, truncate_at, omission: "...") ⇒ void

Parameters:

  • string (#to_s)
  • truncate_at (Integer)
  • omission (String) (defaults to: "...")


48
49
50
51
52
# File 'lib/convenient_service/utils/string/truncate.rb', line 48

def initialize(string, truncate_at, omission: "...")
  @string = string.to_s
  @truncate_at = truncate_at
  @omission = omission
end

Instance Attribute Details

#omissionObject (readonly)

Returns the value of attribute omission.



40
41
42
# File 'lib/convenient_service/utils/string/truncate.rb', line 40

def omission
  @omission
end

#stringObject (readonly)

Returns the value of attribute string.



28
29
30
# File 'lib/convenient_service/utils/string/truncate.rb', line 28

def string
  @string
end

#truncate_atObject (readonly)

Returns the value of attribute truncate_at.



34
35
36
# File 'lib/convenient_service/utils/string/truncate.rb', line 34

def truncate_at
  @truncate_at
end

Instance Method Details

#callString

Returns:



57
58
59
60
61
62
63
64
65
# File 'lib/convenient_service/utils/string/truncate.rb', line 57

def call
  return "" if truncate_at <= 0

  return string if truncate_at >= string.length

  return omission[...truncate_at] if truncate_at <= omission.length

  "#{string[...truncate_at - omission.length]}#{omission}"
end