Module: Entangled::Model::ClassMethods

Defined in:
lib/entangled/model.rb

Instance Method Summary collapse

Instance Method Details

#create_hook(name) ⇒ Object

Creates callbacks in the extented model



59
60
61
# File 'lib/entangled/model.rb', line 59

def create_hook(name)
  send :"after_#{name}", -> { publish(name) }
end

#default_optionsObject

By default, model updates will be published after_create, after_update, and after_destroy. This behavior can be modified by passing :only or :except options to the entangle class method



54
55
56
# File 'lib/entangled/model.rb', line 54

def default_options
  [:create, :update, :destroy]
end

#entangle(options = {}) ⇒ Object

Create after_ callbacks for options



5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
45
46
47
48
# File 'lib/entangled/model.rb', line 5

def entangle(options = {})
  # If :only is specified, the options can either
  # be an array or a symbol
  if options[:only].present?

    # If it is a symbol, something like only: :create
    # was passed in, and we need to create a hook
    # only for that one option
    if options[:only].is_a?(Symbol)
      create_hook options[:only]

    # If it is an array, something like only: [:create, :update]
    # was passed in, and we need to create hook for each
    # of these options
    elsif options[:only].is_a?(Array)
      options[:only].each { |option| create_hook option }
    end

  # Instead of :only, :except can be specified; similarly,
  # the options can either be an array or a symbol
  elsif options[:except].present?
    # If it is a symbol, it has to be taken out of the default
    # options. A callback has to be defined for each of the
    # remaining options
    if options[:except].is_a?(Symbol)
      (default_options - [options[:except]]).each do |option|
        create_hook option
      end

    # If it is an array, it also has to be taen out of the
    # default options. A callback then also has to be defined
    # for each of the remaining options
    elsif options[:except].is_a?(Array)
      (default_options - options[:except]).each do |option|
        create_hook option
      end
    end
  else

    # If neither :only nor :except is specified, simply create
    # a callback for each default option
    default_options.each { |option| create_hook option }
  end
end