Lotus Utils

AKA that gem you'd probably skip over

Jon Cairns / @joonty

What it is

It's a set of classes that provide often-used features (e.g. HTML escaping) or augment existing classes (such as Hash).

We'll take a look at some of the most useful.

Lotus::Utils::Inflector

Pluralises/singularises words, based on standard English rules or a lookup table for the more difficult ones.


require "lotus/utils/inflector"

Lotus::Utils::Inflector.pluralize("cow") #=> "cows"
Lotus::Utils::Inflector.pluralize("sheep") #=> "sheep"
Lotus::Utils::Inflector.pluralize("chicken") #=> "chickina" ??
Lotus::Utils::Inflector.singularize("chickens") #=> "chicken"

Lotus::Utils::Kernel

Adds methods that match common class names, to coerce other object types into these classes.


require "lotus/utils/kernel"

Lotus::Utils::Kernel.Array(true)        # => [true]
Lotus::Utils::Kernel.Integer("1")       # => 1
Lotus::Utils::Kernel.Time('2014-04-18') # => 2014-04-18 00:00:00 +0200

Lotus::Utils::String

Provides methods for changing strings into parameters, constants, etc. Also adds pluralisation methods.


require "lotus/utils/string"

string = Lotus::Utils::String.new 'lotus_utils'
string.classify # => "LotusUtils"
string.titleize # => "Lotus Utils"
string.dasherize # => "lotus-utils"

string = Lotus::Utils::String.new 'chicken'
string.pluralize # => "chickina"

Lotus::Utils::PathPrefix

Create unix-style paths without worrying about separators. Also used for routes.


require "lotus/utils/path_prefix"

path_prefix = Lotus::Utils::PathPrefix.new('posts')
path_prefix.join('new').to_s  # => "/posts/new"
path_prefix.join('/new').to_s # => "/posts/new"

Lotus::Utils::Escape

Safely escape special characters in HTML, HTML attributes and URLs.


require "lotus/utils/escape"

Lotus::Utils::Escape.html('<script>alert(1);</script>')
  #=> "&lt;script&gt;alert(1);&lt;&#x2F;script&gt;"

Lotus::Utils::Escape.html_attribute("some attribute")
  #=> "some&#x20;attribute"

Lotus::Utils::Escape.url("javascript:alert('xss')")
  #=> ""

Lotus::Utils::Attributes

Hash-like object that allows you to access keys with strings or symbols, but stores internally with string keys.


require 'lotus/utils/attributes'

attributes = Lotus::Utils::Attributes.new(a: 1, b: { 2 => [3, 4] })
attributes.to_h # => { "a" => 1, "b" => { "2" => [3, 4] } }

And more

Look up the API docs for more - it's the only place you can.