Training „git“
07.10.2010 - 08.10.2010, Essen
Training „Eclipse RCP“
28.03.2011 - 01.04.2011, Dortmund
05.09.2008

Ruby String helpers

While working on some Ruby scripts, I wrote some String helper methods you might find helpful. Please make sure there will be no naming conflicts in your context before adding methods to the String class.

# Placed in Public Domain by Ralf Ebert, 2008
#
# THIS SOFTWARE IS PROVIDED BY Ralf Ebert ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Ralf Ebert BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

class String

  # Returns an indented string, all lines of string will be indented with count of chars
  def indent(char, count)
    (char * count) + gsub(/(\n+)/) { $1 + (char * count) }
  end

  # Returns string formatted as javadoc comment
  def to_javadoc
    "/**\n" + strip.indent(" * ", 1) + "\n */"
  end

  # Converts this string from markdown markup to html
  # Requires Markdown.pl (http://daringfireball.net/projects/markdown/)
  # to be in path as 'markdown'
  # Download Markdown.pl and create a symbolic link,
  # f.e. "ln -s Markdown.pl /usr/bin/markdown"
  def markdown
    markdown = IO.popen("markdown", "w+") 
    markdown.puts self
    markdown.close_write
    result = markdown.gets(nil)
    markdown.close
    result
  end

  # Converts this string to syntax highlighted html using Python pygments
  # http://pygments.org/
  # Pygments installation: http://pygments.org/docs/installation/
  #   (usually 'sudo easy_install Pygments')
  # Call 'pygmentize -L' for list of available lexers
  # To generate the CSS for the generated HTML: 'pygmentize -S default -f html'
  def pygmentize(lexer)
    pygmentize = IO.popen("pygmentize -f html -l #{lexer}", "w+") 
    pygmentize.puts self
    pygmentize.close_write 
    result = pygmentize.gets(nil)
    pygmentize.close
    result
  end

end

Update: If you’re looking for pygmentize - see also albino: Ruby wrapper for the Pygments syntax highlighter.

I'm looking forward to your comments:

Schulungen

Ruby

Ralf Ebert | Blog | Ruby | Ruby String helpers: indent, to_javadoc, markdown, pygmentize