Module: DataMapper::Audited::InstanceMethods

Defined in:
lib/dm-audited.rb

Instance Method Summary collapse

Instance Method Details

#auditsObject



58
59
60
# File 'lib/dm-audited.rb', line 58

def audits
  Audit.all(:auditable_type => self.class.to_s, :auditable_id => self.id.to_s, :order => [:created_at, :id])
end

#create_audit(action) ⇒ Object



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
51
52
53
54
55
56
# File 'lib/dm-audited.rb', line 16

def create_audit(action)
  # It needs to provide User.current_user if the user is to be saved
  # The implementer needs to provide this and for example needs to make
  # sure that the implementation is thread safe.
  # The request is also optionally included if it can be found in the
  # Application controller. Here again the implementer needs to provide
  # this and make sure it's thread safe.
  user    = defined?(::User)        && ::User.respond_to?(:current_user) && ::User.current_user ? ::User.current_user.id        : nil
  request = defined?(::Application) && ::Application.respond_to?(:current_request)              ? ::Application.current_request : nil

  changed_attributes = {}
  @audited_attributes.each do |key, val|
    changed_attributes[key] = [val, attributes[key]] unless val == attributes[key]
  end

  audit_attributes = {
    :auditable_type => self.class.to_s,
    :auditable_id   => self.id,
    :user_id        => user,
    :action         => action,
    :changes        => changed_attributes
  }

  if request
    params = request.params
    if defined?(::Application) && defined?(Merb::Controller)
      params = Application._filter_params(params)
    end

    audit_attributes.merge!(
      :request_uri    => request.uri,
      :request_method => request.method,
      :request_params => params
    )
  end

  remove_instance_variable("@audited_attributes")
  remove_instance_variable("@audited_new_record") if instance_variable_defined?("@audited_new_record")

  Audit.create(audit_attributes) unless changed_attributes.empty? && action != 'destroy'
end