Module: Mongoid::History::Trackable::ClassMethods

Defined in:
lib/mongoid/history/trackable.rb

Instance Method Summary collapse

Instance Method Details

#disable_tracking(&block) ⇒ Object



56
57
58
59
60
61
# File 'lib/mongoid/history/trackable.rb', line 56

def disable_tracking(&block)
  Thread.current[track_history_flag] = false
  yield
ensure
  Thread.current[track_history_flag] = true
end

#track_history(options = {}) ⇒ Object



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
49
50
# File 'lib/mongoid/history/trackable.rb', line 6

def track_history(options = {})
  scope_name = collection_name.to_s.singularize.to_sym
  default_options = {
    on: :all,
    except: [:created_at, :updated_at],
    modifier_field: :modifier,
    version_field: :version,
    changes_method: :changes,
    scope: scope_name,
    track_create: false,
    track_update: true,
    track_destroy: false,
  }

  options = default_options.merge(options)

  # normalize :except fields to an array of database field strings
  options[:except] = [options[:except]] unless options[:except].is_a? Array
  options[:except] = options[:except].map { |field| database_field_name(field) }.compact.uniq

  # normalize :on fields to either :all or an array of database field strings
  if options[:on] != :all
    options[:on] = [options[:on]] unless options[:on].is_a? Array
    options[:on] = options[:on].map { |field| database_field_name(field) }.compact.uniq
  end

  field options[:version_field].to_sym, type: Integer

  belongs_to_modifier_options = { class_name: Mongoid::History.modifier_class_name }
  belongs_to_modifier_options[:inverse_of] = options[:modifier_field_inverse_of] if options.has_key?(:modifier_field_inverse_of)
  belongs_to options[:modifier_field].to_sym, belongs_to_modifier_options

  include MyInstanceMethods
  extend SingletonMethods

  delegate :history_trackable_options, to: 'self.class'
  delegate :track_history?, to: 'self.class'

  before_update :track_update if options[:track_update]
  before_create :track_create if options[:track_create]
  before_destroy :track_destroy if options[:track_destroy]

  Mongoid::History.trackable_class_options ||= {}
  Mongoid::History.trackable_class_options[scope_name] = options
end

#track_history?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/mongoid/history/trackable.rb', line 52

def track_history?
  Mongoid::History.enabled? && Thread.current[track_history_flag] != false
end

#track_history_flagObject



63
64
65
# File 'lib/mongoid/history/trackable.rb', line 63

def track_history_flag
  "mongoid_history_#{name.underscore}_trackable_enabled".to_sym
end