Skip to content

Commit

Permalink
Change Strings::Truncation to be a class to allow instantiation
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Feb 4, 2021
1 parent 4c65ec4 commit d5e3409
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 6 deletions.
18 changes: 15 additions & 3 deletions lib/strings/truncation.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# frozen_string_literal: true

require "forwardable"
require "strscan"
require "strings-ansi"
require "unicode/display_width"

require_relative "truncation/version"

module Strings
module Truncation
class Truncation
class Error < StandardError; end

DEFAULT_OMISSION = "…".freeze
Expand All @@ -17,6 +18,19 @@ class Error < StandardError; end
ANSI_REGEXP = Regexp.new(Strings::ANSI::ANSI_MATCHER)
RESET_REGEXP = Regexp.new(Regexp.escape(Strings::ANSI::RESET))

# Global instance
#
# @api private
def self.__instance__
@__instance__ ||= Truncation.new
end

class << self
extend Forwardable

delegate %i[truncate] => :__instance__
end

# Truncate a text at a given length (defualts to 30)
#
# @param [String] text
Expand Down Expand Up @@ -95,7 +109,6 @@ def truncate(text, truncate_at = DEFAULT_LENGTH, separator: nil, length: nil,

"#{words.join}#{omission if stop}"
end
module_function :truncate

# Visible width of a string
#
Expand All @@ -105,6 +118,5 @@ def truncate(text, truncate_at = DEFAULT_LENGTH, separator: nil, length: nil,
def display_width(string)
Unicode::DisplayWidth.of(string)
end
module_function :display_width
end # Truncation
end # Strings
6 changes: 3 additions & 3 deletions lib/strings/truncation/version.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# frozen_string_literal: true

module Strings
module Truncation
class Truncation
VERSION = "0.1.0"
end
end
end # Truncation
end # Strings
8 changes: 8 additions & 0 deletions spec/unit/truncate_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@
expect(truncation).to eq("It is not down on an…")
end

it "calls truncate on an instance" do
text = "It is not down on any map; true places never are."
strings = Strings::Truncation.new
truncation = strings.truncate(text, length: 21, separator: " ")

expect(truncation).to eq("It is not down on…")
end

it "truncates with a custom omission" do
text = "It is not down on any map; true places never are."
truncation = Strings::Truncation.truncate(text, 40,
Expand Down

0 comments on commit d5e3409

Please sign in to comment.