Class: RGame::Engine::CachedLabel

Inherits:
Object
  • Object
show all
Defined in:
lib/rgame/engine/cached_label.rb

Overview

Holds a display string and rebuilds it only when its source value changes, so a per-frame draw can show the cached copy without interpolating (allocating) a String every frame. The format block runs only on an actual change.

@score_label = Engine::CachedLabel.new { |score| "Score: #{score}" } # build the block once
renderer.text(@score_label[@score], 12, 10)                          # in on_draw: cached, no alloc

@score_label[value] returns the cached string when value is unchanged, and otherwise rebuilds it through the block. Construct it (and its block) outside the per-frame path — e.g. in on_add — so the interpolation isn't itself a per-frame cost.

Instance Method Summary collapse

Constructor Details

#initialize(&format) ⇒ CachedLabel

Returns a new instance of CachedLabel.

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
# File 'lib/rgame/engine/cached_label.rb', line 16

def initialize(&format)
  raise ArgumentError, 'CachedLabel needs a format block' unless format

  @format = format
  @value = nil
  @text = nil
end

Instance Method Details

#[](value) ⇒ Object

The cached string for value, rebuilt only when value differs from last time.



25
26
27
28
29
30
# File 'lib/rgame/engine/cached_label.rb', line 25

def [](value)
  return @text if !@text.nil? && value == @value

  @value = value
  @text = @format.call(value)
end