Created
June 6, 2012 19:23
-
-
Save danielevans/2884087 to your computer and use it in GitHub Desktop.
Converting Serialized YAML to Serialized JSON in Rails models
This file contains 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 Medium < ActiveRecord::Base | |
serialize :payload, JSON | |
end |
This file contains 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 Medium < ActiveRecord::Base | |
serialize :payload | |
end |
This file contains 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
# create a facade model to avoid validations and other shenanigans | |
faux_medium = Class.new ActiveRecord::Base | |
faux_medium.table_name = "media" | |
# only loading the id and the payload helps avoid certain problems and speeds up the conversion | |
faux_medium.select([:id, :payload]).find_in_batches do |media| | |
media.each do |medium| | |
begin | |
# manually encode to JSON because of the facade class | |
medium.payload = YAML.load(medium.send(:attribute, :payload)).to_json | |
medium.save! | |
rescue Exception => e | |
puts "Could not fix medium #{medium.id} for #{e.message}" | |
end | |
end | |
end |
This file contains 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
hash = { "A" => "B", "C" => "D", "E" => "F", "G" => "H", "I" => { "J" => "K", "L" => "M", "N" => "O", "P" => "Q", "R" => "S" } } | |
yaml = hash.to_yaml | |
json = hash.to_json | |
yaml_time = Benchmark.realtime do | |
1000.times do | |
YAML.load yaml | |
end | |
end # => 5.85665 | |
json_time = Benchmark.realtime do | |
1000.times do | |
JSON.load json | |
end | |
end # => 0.012307 |
Why use medium.send(:attribute, :payload)
while not use medium.payload
directly? My execution raises a error which said "undefined method `asstribute` for the class faux_medium".
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, very useful! 👍