Class: Verso::Base Abstract

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

Overview

This class is abstract.

Classes derived from Verso::Base should define attr_readers or appropriate methods (using Verso::Base#get_attr w/in methods) to access attributes stored in the attrs hash.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Verso::Base

Initialize new object

Parameters:

  • attrs (Hash) (defaults to: {})


21
22
23
# File 'lib/verso/base.rb', line 21

def initialize(attrs={})
  @attrs = attrs.symbolize_nested_keys!
end

Instance Attribute Details

#attrsObject (readonly) Also known as: to_hash

attribute hash



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/verso/base.rb', line 13

class Base
  attr_reader :attrs
  alias to_hash attrs

  # Initialize new object
  #
  # @param attrs [Hash]
  # @return [Verso::Base]
  def initialize(attrs={})
    @attrs = attrs.symbolize_nested_keys!
  end

  # Define methods to retrieve values from attribute hash
  #
  # @param attrs [Symbol]
  def self.attr_reader(*attrs)
    attrs.each do |attr|
      class_eval do
        define_method attr do
          get_attr(attr.to_sym)
        end
      end
    end
  end

protected

  # Get attribute value from attrs attribute store or raise NoMethodError
  # if the key is not defined.
  #
  # @param attr [Symbol]
  # @return attribute value
  # @raise [NoMethodError]
  def get_attr(attr)
    attrs.has_key?(attr) ? attrs[attr] : method_missing(attr)
  end
end

Class Method Details

.attr_reader(*attrs) ⇒ Object

Define methods to retrieve values from attribute hash

Parameters:

  • attrs (Symbol)


28
29
30
31
32
33
34
35
36
# File 'lib/verso/base.rb', line 28

def self.attr_reader(*attrs)
  attrs.each do |attr|
    class_eval do
      define_method attr do
        get_attr(attr.to_sym)
      end
    end
  end
end