Category Archives: Ruby

Ruby: Mixin Template

This is the basic structure I use to create a mixin in Ruby:

# = Mixin Template
# == Usage
# ActionController::Base.send :include, MixinModuleName

module MixinModuleName

def self.included(recipient)
recipient.extend(ClassMethods)
recipient.class_eval do
include InstanceMethods
end
end

module InstanceMethods
end

module ClassMethods
[...]

Ruby: Convert Number to Words (Numerical)

Recently I’ve published my new gem NumberToWords. This plugin/gem will override Ruby’s Numeric class adding a new method called to_words. For now, it only works for Spanish.
Sample usage:

require ‘rubygems’
require ‘number_to_words’
5678.to_words
=> “cinco mil seiscientos setenta y ocho”

Another common usage is for describing currency quantities:

number = 4567.90
=> 4567.9
number.to_words.capitalize << ‘ pesos ‘ << (number.to_s.split(‘.’)[1] || 0).rjust(2,’0′)
=> "Cuatro [...]