4

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
Ossie
  • 1,103
  • 2
  • 13
  • 31

1 Answers1

11

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

Kyle
  • 21,978
  • 2
  • 60
  • 61
  • I don't think I can use version.changeset. As I said above I'm looking at nonadjacent versions so I can't call changeset at all. I'm looking at all versions across all types for my site. That doesn't work with change set. Where would you put the code you've got there? In the model? – Ossie May 22 '14 at 17:17
  • 1
    Heyyyy! "PaperTrail.serializer.load(str)" is a great way of doing it. That's using PaperTrail's method in a way they hadn't thought of right? Excellent. Great answer. – Ossie May 22 '14 at 17:24