Search code examples
ruby-on-railsrubyhashpaper-trail-gem

Paper trail string to hash


Is it possible to convert a string to a hash so it can be iterated over like a hash?

"---
!ruby/hash:ActiveSupport::HashWithIndifferentAccess\ndescription:\n-
Original text blah blah.\n- New text blah blah.\nupdated_at:\n- 2014-05-12 09:18:21.000000000 Z\n-
2014-05-12 09:19:33.748593000 Z\n"

I'm using the paper_trail gem and trying to do diffing of non-adjacent versions. This prevents me from using the built-in "changeset" hash, which does what I want.

Using many regexes, I could deal with these strings, but I want to turn them into hashes where "description" would be taken as a key and the next two items would be value.first and value.last.

The string is called with <%= version.object_changes %>. How could I call that as a hash?


Solution

  • You should use version.changeset to get a parsed hash of the objects changes.

    If you really want to convert that string into the ruby object (ActiveSupport::HashWithIndifferentAccess), you can:

    str = "--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess\ndescription..."
    YAML.load(str)
    # => {"description"=>["Original text blah blah.", "New text blah blah."], "updated_at"=>[2014-05-12 09:18:21 UTC, 2014-05-12 09:19:33 UTC]}
    
    # or
    PaperTrail.serializer.load(str)
    

    see Papertrail::VersionConcern.changeset