Created
July 6, 2016 02:46
-
-
Save ToQoz/4cd91cf2e3fa8acb2a5b9b6a33aa22f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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