Module: Tracksperanto::Safety

Included in:
Import::Base
Defined in:
lib/tracksperanto/safety.rb

Overview

Implements the safe_reader class method which will define (or override) readers that raise if ivar is nil

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(into) ⇒ Object



5
6
7
8
# File 'lib/tracksperanto/safety.rb', line 5

def self.included(into)
  into.extend(self)
  super
end

Instance Method Details

#safe_reader(*attributes) ⇒ Object

Inject a reader that checks for nil



11
12
13
14
15
16
17
18
19
20
# File 'lib/tracksperanto/safety.rb', line 11

def safe_reader(*attributes)
  attributes.each do | an_attr |
    alias_method "#{an_attr}_without_nil_protection", an_attr
    define_method(an_attr) do
      val = send("#{an_attr}_without_nil_protection")
      raise "Expected #{an_attr} on #{self} not to be nil" if val.nil?
      val
    end
  end
end