Class: Class

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

Overview

Class

Instance Method Summary collapse

Instance Method Details

#attr_set_once(*atts) ⇒ Object

attr_set_once



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/setonce.rb', line 6

def attr_set_once(*atts)
  atts.each do |att|
    att = att.to_s
    
    # set
    define_method("#{att}=") do |val|
      if instance_variable_defined?("@#{att}")
        raise 'set-once-instance-variable-already-set: ' + att
      else
        instance_variable_set "@#{att}", val
      end
    end
    
    # get
    define_method("#{att}") do
      if instance_variable_defined?("@#{att}")
        return instance_variable_get("@#{att}")
      else
        return nil
      end
    end
  end
end