Class: BackgroundLite::DrbHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/background_lite/core_ext/handlers/drb_handler.rb

Overview

This background handler sends the method as well as the arguments through DRb to the background process.

Class Method Summary collapse

Class Method Details

.background_queueObject



5
6
7
8
9
10
11
12
# File 'lib/background_lite/core_ext/handlers/drb_handler.rb', line 5

def self.background_queue
  @background_queue ||= begin
    require 'drb'
    
    DRb.start_service
    DRbObject.new(nil, "druby://localhost:2251")
  end
end

.decode(message) ⇒ Object

Decodes a marshalled message which was previously sent over DRb. Returns an array containing the object, the method name as a string, and the method arguments.



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/background_lite/core_ext/handlers/drb_handler.rb', line 23

def self.decode(message)
  begin
    object, method, args = Marshal.load(message)
  rescue ArgumentError => e
    # Marshal.load does not trigger const_missing, so we have to do this
    # ourselves.
    e.message.split(' ').last.constantize
    retry
  end
  [object, method, args]
end

.execute(message) ⇒ Object

Executes a marshalled message which was previously sent over DRb, in the context of the object, with all the arguments passed.



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/background_lite/core_ext/handlers/drb_handler.rb', line 38

def self.execute(message)
  begin
    object, method, args = self.decode(message)
    puts "--- executing method: #{method}\n--- with variables: #{args.inspect}\n--- in object: #{object.class.name}, #{object.id}"

    object.send(method, *args)
    puts "--- it happened!"
  rescue Exception => e
    puts e.message
    puts e.backtrace
  end
end

.handle(object, method, args, options = {}) ⇒ Object

Marshals the method and the arguments and sends it through DRb to the background process.



16
17
18
# File 'lib/background_lite/core_ext/handlers/drb_handler.rb', line 16

def self.handle(object, method, args, options = {})
  background_queue.push(Marshal.dump([object, method, args]))
end