Skip to content

Instantly share code, notes, and snippets.

@ToQoz
Created July 6, 2016 02:46
Show Gist options
  • Select an option

  • Save ToQoz/4cd91cf2e3fa8acb2a5b9b6a33aa22f2 to your computer and use it in GitHub Desktop.

Select an option

Save ToQoz/4cd91cf2e3fa8acb2a5b9b6a33aa22f2 to your computer and use it in GitHub Desktop.
# 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