Class: Module

Inherits:
Object show all
Defined in:
lib/shenanigans/module/private_accessor.rb

Instance Method Summary collapse

Instance Method Details

#private_accessor(*names) ⇒ Object

Works like attr_accessor but generates private getter/setter methods for class internal use only. Useful for enforcing Smalltalk-style internal encapsulation.

For a more complete implementation of a similar feature see ivar_encapsulation.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/shenanigans/module/private_accessor.rb', line 7

def private_accessor(*names)
  names.each do |name|
    instance_var_name = "@#{name}"

    define_method(name) do
      instance_variable_get(instance_var_name)
    end

    define_method("#{name}=") do |value|
      instance_variable_set(instance_var_name, value)
    end

    send(:private, name)
    send(:private, "#{name}=")
  end
  nil # like attr_accessor
end