class Ceres::Reader

Attributes

attribute[R]
block[R]

Public Class Methods

new(attribute, cache: false, &block) click to toggle source
# File lib/ceres/reader.rb, line 6
def initialize(attribute, cache: false, &block)
  @attribute = attribute
  @cache = cache
  @block = block
end

Public Instance Methods

apply(klass) click to toggle source
# File lib/ceres/reader.rb, line 32
def apply(klass)
  name = self.name

  if allow_reader_optimisation?
    klass.instance_exec { attr_reader name }
  else
    reader = self.to_proc

    klass.instance_exec { define_method(name, &reader) }
  end
end
cache?() click to toggle source
# File lib/ceres/reader.rb, line 12
def cache?
  @cache
end
name() click to toggle source
# File lib/ceres/reader.rb, line 16
def name
  @attribute.name
end
target() click to toggle source
# File lib/ceres/reader.rb, line 20
def target
  @attribute.target
end
to_proc() click to toggle source
# File lib/ceres/reader.rb, line 28
def to_proc
  self.cache? ? to_cached_proc : to_uncached_proc
end
variable() click to toggle source
# File lib/ceres/reader.rb, line 24
def variable
  @attribute.variable
end

Private Instance Methods

allow_reader_optimisation?() click to toggle source
# File lib/ceres/reader.rb, line 44
        def allow_reader_optimisation?
  !@block && self.target.nil? && self.variable == "@#{self.name}".to_sym
end
to_cached_proc() click to toggle source
# File lib/ceres/reader.rb, line 64
        def to_cached_proc
  uncached_proc = to_uncached_proc
  variable = self.variable

  proc do
    if instance_variable_defined?(variable)
      instance_variable_get(variable)
    else
      instance_variable_set(variable, instance_exec(&uncached_proc))
    end
  end
end
to_uncached_proc() click to toggle source
# File lib/ceres/reader.rb, line 48
        def to_uncached_proc
  target = self.target
  variable = self.variable
  block = self.block

  if target
    if block
      proc { instance_variable_get(target).instance_exec(&block) }
    else
      proc { instance_variable_get(target).instance_variable_get(variable) }
    end
  else
    block || proc { instance_variable_get(variable) }
  end
end