Class: LiveResource::ActiveRecord::Dependency

Inherits:
Dependency
  • Object
show all
Defined in:
lib/live_resource/activerecord/dependency.rb

Constant Summary collapse

DEFAULT_EVENTS =
[:after_commit]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, model_class, proc, *events) ⇒ Dependency

Returns a new instance of Dependency.



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/live_resource/activerecord/dependency.rb', line 16

def initialize(resource, model_class, proc, *events)
  @model_class = model_class

  if !events.empty?
    @events = events
  else
    @events = DEFAULT_EVENTS
  end

  super(resource, model_class, proc)
end

Instance Attribute Details

#model_classObject (readonly)

Returns the value of attribute model_class.



14
15
16
# File 'lib/live_resource/activerecord/dependency.rb', line 14

def model_class
  @model_class
end

#resourceObject (readonly)

Returns the value of attribute resource.



14
15
16
# File 'lib/live_resource/activerecord/dependency.rb', line 14

def resource
  @resource
end

Class Method Details

.accepts_target?(target) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/live_resource/activerecord/dependency.rb', line 10

def self.accepts_target?(target)
  !!(target < ::ActiveRecord::Base) # The < operator returns nil instead of false
end

Instance Method Details

#observe(event) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/live_resource/activerecord/dependency.rb', line 32

def observe(event)
  # Declare variables in method scope so they're preserved in the block
  dependency          = self
  subscribed_events   = @events
  target              = @model_class
  class_name          = "Observer_#{@resource.name}_dependency_on_#{@model_class}_for_#{@events.join('_')}"

  # Construct a new observer class
  dependency_observer = Class.new(::ActiveRecord::Observer) do
    observe target

    # Give it a class name otherwise ActiveRecord will explode
    @_class_name = class_name
    class << self
      def name
        @_class_name
      end
    end

    # Create callback methods on the observer class for each subscribed event
    subscribed_events.each do |event_name|
      define_method(event_name) do |*args|
        dependency.invoke(args[0], event_name)
      end
    end
  end

  # Instantiating the observer class will make it hook itself up
  dependency_observer.send :new
end

#watchObject



28
29
30
# File 'lib/live_resource/activerecord/dependency.rb', line 28

def watch
  @events.each { |event| observe event }
end