Sha256: 5d6cd78c4269a32f955985cfb4df847fae5c9e17d65bd1a5be34d5520914d147

Contents?: true

Size: 1.57 KB

Versions: 2

Compression:

Stored size: 1.57 KB

Contents

#
# File::      StringFormatting.rb
# Author::    wkm
# Copyright:: 2009
# License::   GPL
#
# Adds String#cabbrev for abbreviating strings
#

class String

  # gives an abbreviated form of a string, showing some of the beginning
  # and some of the end.
  # 
  #  "the quick brown dog".cabbrev 12  # => "the q... dog"
  def cabbrev(len)
    if length <= len
      self
    else
      self[0..(len/2-2).floor] + "..." + self[(length - len/2+2) .. (length)]
    end
  end

  # gives an abbreviated form of the string, showing as much of the beginning
  # as possible
  #
  #  "the quick brown dog".labbrev 12  # => "the quick ..."
  def labbrev(len)
    if length <= len
      self
    else
      self[0..(len-4)] + '...'
    end
  end

  # gives an abbreviated form of the string, showing as much of the end as
  # possible
  #
  #  "the quick brown dog".rabbrev 12  # => "...brown dog"
  def rabbrev(len)
    if length <= len
      self
    else
      '...' + self[(length - (len-3)) .. length]
    end
  end

  # removes leading whitespace from a set of lines, preserving indentation
  # relative to the first non-empty line
  def align
    return self if empty?

    # split by lines
    lines = split("\n")

    # get rid of the first line if it is null
    if lines.first == ''
      lines = lines[1..-1]
    end

    # take the first line and extract the leading whitespace
    leading = lines.first[/^[ \t]*/]

    # iterate over each line dumping the leading whitespace
    lines = lines.map do |l|
      l.gsub!(Regexp.new('^'+leading), '')
    end

    lines.join("\n")
  end


  alias :format :%

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sitefuel-0.0.0b lib/sitefuel/extensions/StringFormatting.rb
sitefuel-0.0.0a lib/sitefuel/extensions/StringFormatting.rb