Module: InterProcessAttribute

Included in:
Class
Defined in:
lib/interprocess_attribute.rb

Instance Method Summary collapse

Instance Method Details

#interprocess_attribute(*args) ⇒ Object

Examples:

class Person
  extend InterProcessAttribute
  interprocess_attribute :name, :age
end

person = Person.new
pid = fork do
  person.name = "Rob"
  person.age = 27
end
Process.wait pid
p person.name # => "Rob"
p person.age # => 27


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
# File 'lib/interprocess_attribute.rb', line 19

def interprocess_attribute(*args)
  Hash === args.last ? (opts = args.pop) : (opts = {visibility: "public"})
  attributes = args
  if attributes.empty?
    raise ArgumentError,
      "Wrong number of arguments (no attribute names given)"
  end
  class_eval do
    attributes.each do |name|
      channel = IChannel.new Marshal
      define_method name do
        while channel.readable?
          instance_variable_set "@#{name}", channel.get
        end
        instance_variable_get "@#{name}"
      end
      send opts[:visibility], name.to_sym

      define_method "#{name}=" do |value|
        channel.put value
        instance_variable_set "@#{name}", value
      end
      send opts[:visibility], "#{name}=".to_sym
    end
  end
end