Last active
May 3, 2016 09:17
-
-
Save amitpatelx/232434b971e132125920e0212ea6d6b3 to your computer and use it in GitHub Desktop.
Hash to YAML - Used to convert hash to YAML and save in a fixture file.
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
#asumpution - Hash contains all keys as symbols | |
hash = {:post_id=>"11468", | |
:post_title=>"Post with short sommary", | |
:post_date=>{:year=>2016, :month=>4, :day=>29, :hour=>9, :min=>20, :sec=>12}} | |
#1. deep_stringify_keys! - Destructively convert all keys to strings. This includes the keys from the root hash and from all nested hashes and arrays. | |
hash.deep_stringify_keys! | |
#2. Write to file | |
file = 'path/to/output/file.txt' | |
File.open(file, 'w') { |file| file.write( hash.to_yaml) } | |
#3. Read from yaml back to hash | |
hash = YAML.load(File.read(file)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment