Module: Feature::Cache

Defined in:
lib/feature/cache.rb

Overview

Provide simple value caching through the cache private method.

require "feature/cache"

class Person
  Feature::Cache.load(self)

  attr_reader :first_name
  attr_reader :last_name

  def full_name
    # This value is cached.
    cache[:full_name] ||= "#{first_name} #{last_name}"
  end

  def first_name=(s)
    cache.clear
    @first_name = s
  end

  def last_name=(s)
    cache.clear
    @last_name = s
  end
end

Defined Under Namespace

Modules: DefaultMode, InvisibleMode

Class Method Summary collapse

Class Method Details

.load(owner, options = {}) ⇒ Object

Activate feature.

class Klass
  # Default mode.
  Feature::Cache.load(self)                       # Default mode.

  # Invisible mode. Cache will be hidden from `.inspect`.
  Feature::Cache.load(self, invisible: true)      # Invisible mode.

  ...
end

Options:

:invisible => T|F         # Cache values will not be visible via `inspect`. Default is `false`.

Raises:

  • (ArgumentError)

47
48
49
50
51
52
53
54
55
56
57
# File 'lib/feature/cache.rb', line 47

def self.load(owner, options = {})
  o = {}
  options = options.dup
  o[k = :invisible] = options.include?(k) ? options.delete(k) : false
  raise ArgumentError, "Unknown options: #{options.inspect}" if not options.empty?

  # Activation check.
  return if owner < DefaultMode::InstanceMethods or owner < InvisibleMode::InstanceMethods

  owner.send(:include, o[:invisible] ? InvisibleMode::InstanceMethods : DefaultMode::InstanceMethods)
end