Class: LazyString

Inherits:
Object
  • Object
show all
Defined in:
lib/lazy_string.rb

Overview

LazyString is a class for computing strings only when necessary. This is useful when computing the string is expensive but the string is unlikely to be used: an error message passed as an argument, for example.

Constant Summary collapse

VERSION =

The version string.

'0.4.0'

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ LazyString

Creates a new lazy string. The block argument will be saved for later use by #to_str. If no block argument is given, it will default to a block that returns an empty string.



17
18
19
# File 'lib/lazy_string.rb', line 17

def initialize(&block)
  @block = block || lambda { '' }
end

Instance Method Details

#to_sObject

A synonym for #to_str.



24
25
26
# File 'lib/lazy_string.rb', line 24

def to_s
  to_str
end

#to_strObject

Returns the computed string. It will compute the string by calling (with no arguments) the block passed to ::new. If the block's return value responds to the to_str message, to_str will be sent to it to create the string. Otherwise, to_s will be sent to it. The computed string will be saved, so subsequent invocations of this method will not cause the block to be called again.



36
37
38
39
40
41
42
43
44
45
# File 'lib/lazy_string.rb', line 36

def to_str
  @str ||= begin
    result = @block.call
    if result.respond_to?(:to_str)
      result.to_str
    else
      result.to_s
    end
  end
end