Sha256: 555695ce4a7bb5c4c192bfca433f5ee7c98411ba1f7f3b5474a2a0ec7b11d929

Contents?: true

Size: 1.41 KB

Versions: 5

Compression:

Stored size: 1.41 KB

Contents

# frozen_string_literal: true

require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/filters'
require 'active_support/core_ext/string/output_safety'

String.class_eval do
  # Cuts off a long string and will add an ellipsis or
  # what has been entered via +:end_more+ option.
  #
  # @param max [Integer] Max string length in characters
  # @param options [Hash]
  #
  # @option options [Boolean] :ending This will add the
  #   ellipsis in the middle of the word instead of the
  #   end, which will show the start and end of the string.
  #
  # @option options [String] :end_more Instead of showing
  #   and ellipsis at the end of the string, it will show
  #   this string. This will be counted against the max
  #   and will only show up once the max is hit.
  #   *This is ignored when +:ending+ enabled.*
  #
  # @return [String]
  #
  def cutoff(max = 60, options = {})
    this = self
    max_len = (max || 60).to_i
    opts = { ending: false, end_more: nil }.merge(options || {})

    # Return the string if it isn't over the max
    return this if this.size < max_len

    end_chars = opts[:end_more].present? ? opts[:end_more] : '...'

    unless opts[:ending]
      return this.truncate(max_len, { omission: end_chars }).html_safe
    end

    start_val = ((max_len - 3) / 2).round
    end_val = max_len - start_val

    "#{this[0, start_val]}...#{this[-end_val, this.size]}".html_safe
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ruby-rails-extensions-2.1.2 lib/ruby-rails-extensions/extensions/cutoff.rb
ruby-rails-extensions-2.1.2.pre.pre.pre.1 lib/ruby-rails-extensions/extensions/cutoff.rb
ruby-rails-extensions-2.1.1 lib/ruby-rails-extensions/extensions/cutoff.rb
ruby-rails-extensions-2.1.0 lib/ruby-rails-extensions/extensions/cutoff.rb
ruby-rails-extensions-2.1.0.pre.rc.14 lib/ruby-rails-extensions/extensions/cutoff.rb