What is rol?
rol creates Ruby objects from a hash of attributes and methods:
require 'rol'
object = rol({
width: 2,
height: 3,
area: -> { @width * @height },
scale: -> (factor) {
@width *= factor
@height *= factor
}
})
print object.width, ' ', object.height, ' ', object.area, "\n" # => 2 3 6
object.width = 4
print object.width, ' ', object.height, ' ', object.area, "\n" # => 4 3 12
object.scale(10)
print object.width, ' ', object.height, ' ', object.area, "\n" # => 40 30 1200
Installation
$ gem install rol
To uninstall:
$ gem uninstall rol
Usage
rol provides a quick way to create objects on the fly without having to create a full class. For example, the following creates an object with an attribute x that is initialized to the value 3:
require 'rol'
coord = rol({ x: 3 })
puts coord.x # => 3
Attributes can be assigned:
require 'rol'
coord = rol({ x: 3 })
puts coord.x # => 3
coord.x = 7
puts coord.x # => 7
Methods can also be defined:
require 'date'
require 'rol'
due_date = rol({ formatted: -> { Date.new(2014,11,24).strftime('%Y.%m.%d') } })
puts due_date.formatted # => 2014.11.24
Methods can take arguments:
require 'rol'
friendly = rol({ greet: -> (name) { "Hi #{name}!" } })
puts friendly.greet('Spot') # => Hi Spot!
Attributes are defined as instance variables and are therefore accessible from methods:
require 'rol'
counter = rol({
current: 0,
increment: -> { @current += 1 }
})
puts counter.current # => 0
counter.increment
puts counter.current # => 1
Equivalents
Using rol to define an attribute:
object = rol({ x: 123 })
puts object.x # => 123
is equivalent to:
object = Object.new
def object.x
@x
end
def object.x=(value)
@x = value
end
object.x = 123
puts object.x # => 123
Using rol to define a method:
object = rol({
my_method: -> (arg) { puts arg }
})
object.my_method(123) # => 123
is equivalent to:
object = Object.new
def object.my_method(arg)
puts arg
end
object.my_method(123) # => 123
Development Documentation
Here.