[LRUG] Serialising a struct

Stephen Nelson-Smith sanelson at gmail.com
Mon Apr 14 09:37:31 PDT 2014


Hi,

On Mon, Apr 14, 2014 at 3:50 PM, Stephen Nelson-Smith <sanelson at gmail.com>wrote:


> I'm currently thinking something like (untested, caffeinated):
>
> images = ec2.describe_images(owners: ['self']).images.map(&:to_h)
> serialised_images = images.to_json
> MyEc2Struct = Struct.new(images.keys)
> canned_images = serialised_images.reduce(MyEc2Struct.new) {|s, kv|
> s[kv[0]] = kv[1]; s}
>

OK so:


images = ec2.describe_images(owners: ['self']).images.[1..3]
[10] pry(main)> images[0].image_id
=> "ami-00ccc374"
[11] pry(main)> images[0].name
=> "64-bit Debian 6.0 EBS (1.8) 2013-01-11"
File.write('serialised_images.json', images.map(&:to_h).to_json)

--- New Session ---

require 'json'
images = JSON.parse(serialised_images)
Images = Struct.new(*images[0].keys.map(&:to_sym))
Images.members
=> [:image_id,
 :image_location,
 :state,
 :owner_id,
 :public,
 :product_codes,
 :architecture,
 :image_type,
 :kernel_id,
 :ramdisk_id,
 :platform,
 :sriov_net_support,
 :state_reason,
 :image_owner_alias,
 :name,
 :description,
 :root_device_type,
 :root_device_name,
 :block_device_mappings,
 :virtualization_type,
 :tags,
 :hypervisor]

original = images.map { |img| img.reduce(Images.new) { |s, kv| s[kv[0]] =
kv[1]; s } }
[21] pry(main)> original[0].name
=> "64-bit Debian 6.0 EBS (1.8) 2013-01-11"
[22] pry(main)> original[0].image_id
=> "ami-00ccc374"

Not perfect, as there are some nested structs (eg tags) but it's a start!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20140414/0ffd0063/attachment-0003.html>


More information about the Chat mailing list