SHARE
TWEET

Untitled

a guest Jun 25th, 2019 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # File: ruby-serialization-2.rb
  2. #
  3. require 'Date'
  4. require 'json'
  5.  
  6. class Customer
  7.   attr_accessor :name,
  8.                 :address
  9.  
  10.   def initialize(name, address)
  11.     @name = name
  12.     @address = address
  13.   end
  14.  
  15.   def to_h
  16.     {name: name,
  17.      address: address}
  18.   end
  19.  
  20.   def self.from_h(customer_hash)
  21.     new(customer_hash['name'], customer_hash['address'])
  22.   end
  23. end
  24.  
  25. class OrderItem
  26.   attr_accessor :id,
  27.                 :item,
  28.                 :item_type,
  29.                 :price,
  30.                 :currency
  31.  
  32.   def initialize(id, item, item_type, price, currency)
  33.     @id = id
  34.     @item = item
  35.     @item_type = item_type
  36.     @price = price
  37.     @currency = currency
  38.   end
  39.  
  40.   def to_h
  41.     {id: id, item: item, item_type: item_type, price: price, currency: currency}
  42.   end
  43.  
  44.   def self.from_h(order_item_hash)
  45.     new(
  46.       order_item_hash['id'],
  47.       order_item_hash['item'],
  48.       order_item_hash['item_type'],
  49.       order_item_hash['price'],
  50.       order_item_hash['currency']
  51.     )
  52.   end
  53. end
  54.  
  55. class Order
  56.   attr_accessor :order_number,
  57.                 :order_date,
  58.                 :customer,
  59.                 :order_details
  60.   def to_json(*options)
  61.     {order_number: order_number,
  62.      order_date: order_date,
  63.      customer: customer.to_h,
  64.      order_details: order_details.map(&:to_h) }.to_json(options)
  65.   end
  66.  
  67.   def self.from_json(order_json)
  68.     order_hash = JSON.parse(order_json)
  69.     order = Order.new
  70.     order.order_number = order_hash['order_number']
  71.     order.order_date = order_hash['order_date']
  72.     order.customer = Customer.from_h(order_hash['customer'])
  73.     order.order_details = order_hash['order_details'].map {|order_item_hash| OrderItem.from_h(order_item_hash)}
  74.     order
  75.   end
  76. end
  77.  
  78. order_json = File.read('order.json')
  79.  
  80. order = Order.from_json(order_json)
  81. puts order.inspect
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top