Class: ActiveTouch::DefineTouch

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, association, options) ⇒ DefineTouch

Returns a new instance of DefineTouch.



10
11
12
13
14
15
# File 'lib/active_touch/define_touch.rb', line 10

def initialize(klass, association, options)
  @klass = klass
  @association = association
  @options = default_options.merge(options)
  @touch_method = "touch_#{SecureRandom.uuid}"
end

Class Method Details

.on(klass, association, options) ⇒ Object



4
5
6
7
8
# File 'lib/active_touch/define_touch.rb', line 4

def self.on(klass, association, options)
  new(klass, association, options).define if ActiveRecord::Base.connection.table_exists?(klass.table_name)
rescue ActiveRecord::NoDatabaseError
  # do nothing
end

Instance Method Details

#add_active_record_callbackObject



48
49
50
51
# File 'lib/active_touch/define_touch.rb', line 48

def add_active_record_callback
  touch_method = @touch_method
  @klass.send(:after_commit) { send(touch_method) }
end

#add_to_networkObject



53
54
55
56
# File 'lib/active_touch/define_touch.rb', line 53

def add_to_network
  touched = @options[:class_name] || @association.to_s.camelize
  ActiveTouch.network.add_touch(@klass.to_s, touched, @options[:watch])
end

#default_optionsObject



58
59
60
61
62
63
64
65
66
# File 'lib/active_touch/define_touch.rb', line 58

def default_options
  {
      async: ActiveTouch.configuration.async,
      watch: @klass.column_names.map(&:to_sym) - ActiveTouch.configuration.ignored_attributes,
      after_touch: nil,
      if: Proc.new { true },
      unless: Proc.new { false }
  }
end

#defineObject



17
18
19
20
21
# File 'lib/active_touch/define_touch.rb', line 17

def define
  define_touch_method
  add_active_record_callback
  add_to_network
end

#define_touch_methodObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/active_touch/define_touch.rb', line 23

def define_touch_method
  association = @association
  options = @options

  @klass.send :define_method, @touch_method do |*args|
    changed_attributes = self.previous_changes.keys.map(&:to_sym)
    watched_changes = (options[:watch] & changed_attributes)

    # watched values changed and conditional procs evaluate to true
    if watched_changes.any? && options[:if].call(self) && !options[:unless].call(self)
      Rails.logger.debug "Touch: #{self.class}(#{self.id}) => #{association} due to changes in #{watched_changes}"

      if options[:async]
        TouchJob
            .set(queue: ActiveTouch.configuration.queue)
            .perform_later(self, association.to_s, options[:after_touch].to_s, true)

      else
        TouchJob.perform_now(self, association.to_s, options[:after_touch].to_s, false)
      end

    end
  end
end