Skip to content

Commit

Permalink
Cleanup TextHelpers module.
Browse files Browse the repository at this point in the history
- Add delimit method i.e. delimit(1000) == 1,000.
- Make titlecase use mutating string manipulation methods.
- Make underscore more robust.
- Add additional tests (and rename test to match the actual file).
  • Loading branch information
Cyril David committed Jul 12, 2012
1 parent 6f4bd87 commit b0e76ed
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 35 deletions.
21 changes: 13 additions & 8 deletions lib/cuba/contrib/text_helpers.rb
@@ -1,9 +1,7 @@
class Cuba
module TextHelpers
def markdown(str)
require "bluecloth"

BlueCloth.new(str).to_html
Markdown.new(str).to_html
end

def truncate(str, length, ellipses = "...")
Expand All @@ -20,16 +18,23 @@ def currency(amount, unit = "$")
"#{unit} %.2f" % amount
end

def titlecase(str)
str.to_s.tr("_", " ").gsub(/(^|\s)([a-z])/) { |char| char.upcase }
def delimit(number, delimiter = ",")
number.to_s.gsub(%r{(\d)(?=(\d\d\d)+(?!\d))}, "\\1#{delimiter}")
end

def humanize(str)
titlecase(str.to_s.tr("_", " ").gsub(/_id$/, ""))
def titlecase(str)
res = str.to_s.dup
res.tr!("_", " ")
res.gsub!(/(^|\s)([a-z])/) { |char| char.upcase }
res
end

def underscore(str)
str.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').downcase
res = str.to_s.dup
res.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
res.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
res.downcase!
res
end
end
end
27 changes: 0 additions & 27 deletions test/text_helper.rb

This file was deleted.

46 changes: 46 additions & 0 deletions test/text_helpers.rb
@@ -0,0 +1,46 @@
# encoding: utf-8

require_relative "helper"

setup do
obj = Object.new
obj.extend Cuba::TextHelpers
end

test "truncate" do |helper|
assert_equal "the q...", helper.truncate("the quick brown", 5)

assert_equal "same string", helper.truncate("same string", 11)
end

test "markdown" do |helper|
require "bluecloth"
assert_equal "<h1>Hola Mundo</h1>", helper.markdown("# Hola Mundo")
end

test "nl2br" do |helper|
assert_equal "Hi<br>there<br>Joe", helper.nl2br("Hi\nthere\r\nJoe")
end

test "currency" do |helper|
assert_equal "$ 2.22", helper.currency(2.221)
assert_equal "€ 2.22", helper.currency(2.221, "€")
end

test "delimit" do |helper|
assert_equal "2,000", helper.delimit(2000)
assert_equal "2.000", helper.delimit(2000, ".")
assert_equal "2,000,000", helper.delimit(2000000)
assert_equal "2,000,000.05", helper.delimit(2000000.05)
end

test "titlecase" do |helper|
assert_equal "Hello World", helper.titlecase("hello world")
end

test "underscore" do |helper|
assert_equal "foo_bar_baz", helper.underscore("FooBarBaz")
assert_equal "ohm_v1_foo", helper.underscore("OhmV1Foo")
assert_equal "ssl_error", helper.underscore("SSLError")
assert_equal "net_http", helper.underscore("NetHTTP")
end

0 comments on commit b0e76ed

Please sign in to comment.