-
-
Save EveDreamer/f7ea3f991526a9bcbca2ec1d5e866107 to your computer and use it in GitHub Desktop.
Converting Serialized YAML to Serialized JSON in Rails models
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 Medium < ActiveRecord::Base | |
serialize :payload, JSON | |
end |
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 Medium < ActiveRecord::Base | |
serialize :payload | |
end |
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
# 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 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment