Class: RVGP::Base::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/rvgp/base/reader.rb

Overview

This base class exists as a shorthand, for classes whose public readers are populated via #initialize(). Think of this as an lighter-weight alternative to OpenStruct.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#optionsHash<Symbol,Object> (readonly)

This instance’s reader attributes, and their values, as a Hash

Returns:

  • (Hash<Symbol,Object>)

    the current value of options



8
9
10
# File 'lib/rvgp/base/reader.rb', line 8

def options
  @options
end

Class Method Details

.readers(*readers) ⇒ Object

Classes which inherit from this class, can declare their attr_reader in a shorthand format, by way of this method. Attributes declared in this method, will be able to be set in the options passed to their #initialize

Parameters:

  • readers (Array<Symbol>)

    A list of the attr_readers, this class will provide



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rvgp/base/reader.rb', line 13

def self.readers(*readers)
  attr_reader(*readers)
  attr_reader :options

  define_method :initialize do |*args|
    readers.each_with_index do |r, i|
      instance_variable_set format('@%s', r).to_sym, args[i]
    end

    # If there are more arguments than attr's the last argument is an options
    # hash
    instance_variable_set '@options', args[readers.length].is_a?(Hash) ? args[readers.length] : {}
  end
end