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.



8
9
10
11
12
13
# File 'lib/active_touch/define_touch.rb', line 8

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
# File 'lib/active_touch/define_touch.rb', line 4

def self.on(klass, association, options)
  new(klass, association, options).define
end

Instance Method Details

#add_active_record_callbackObject



39
40
41
42
# File 'lib/active_touch/define_touch.rb', line 39

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

#default_optionsObject



44
45
46
47
48
49
50
# File 'lib/active_touch/define_touch.rb', line 44

def default_options
  {
      async: false,
      watch: @klass.column_names.map(&:to_sym),
      after_touch: nil
  }
end

#defineObject



15
16
17
18
# File 'lib/active_touch/define_touch.rb', line 15

def define
  define_touch_method
  add_active_record_callback
end

#define_touch_methodObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/active_touch/define_touch.rb', line 20

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)

    if (options[:watch] & changed_attributes).any?

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

    end
  end
end