Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
# class User < ActiveRecord::Base
# include ActiveRecordSelfDiff
# end
#
# u = User.create(name: "toqoz")
# u.name = "toqoz-2"
# u.self_diff
# => {"name" => #<struct Struct::Diff old="toqoz", now="toqoz-2">}
module ActiveRecordSelfDiff
DIFF = Struct.new("Diff", :old, :now)
def self_diff
attributes.keys.
select { |attr| send("#{attr}_changed?") }.
reduce({}) { |diff, attr|
diff[attr] = DIFF.new(send("#{attr}_was"), send(attr))
diff
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment