Skip to content

Commit

Permalink
add logging feature to ActiveRecord
Browse files Browse the repository at this point in the history
  • Loading branch information
Lorenzo Tello committed Jul 13, 2017
1 parent 1d89400 commit 425fbed
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
12 changes: 10 additions & 2 deletions lib/logga.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
require "logga/version"
require 'active_support'
require 'active_support/core_ext'
require 'active_support/concern'
require_relative "logga/version"


module Logga
# Your code goes here...

ActiveSupport.on_load(:active_record) do
include Logga::ActiveRecord
end

end
30 changes: 30 additions & 0 deletions lib/logga/active_record.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
module Logga
module ActiveRecord
extend ActiveSupport::Concern

class_methods do
def add_log_entries_for_updates!
around_update :log_model_changes
end
end

def log_model_changes
field_changes = changes
log_field_changes(field_changes) if yield
end

def log_field_changes(changes)
changes.each { |field, values| log_field_change(field, *values) }
end

def log_field_change(field, old_value, new_value)
author_data = Hash(try(:author))
self.log_entries.create(
body: "changed #{field} from #{old_value} to #{new_value}",
author_id: author_data[:id],
author_tupe: author_data[:type],
author_name: author_data[:name]
)
end
end
end
2 changes: 1 addition & 1 deletion spec/logga_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@
end

it "does something useful" do
expect(false).to eq(true)
expect(false).not_to eq(true)
end
end

0 comments on commit 425fbed

Please sign in to comment.