Skip to content

Commit

Permalink
"order" example refined
Browse files Browse the repository at this point in the history
  • Loading branch information
multi-io committed Feb 13, 2005
1 parent 8815660 commit 05f4470
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 4 deletions.
8 changes: 6 additions & 2 deletions examples/order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ class Order
text_node :reference, "@reference"
object_node :client, Client, "Client"
hash_node :items, Item, "Item", "@reference"
array_node :signatures, Signature, "Signatures", "Signed-By"
array_node :signatures, Signature, "Signatures", "Signed-By", :optional=>true, :default_value=>[]

def total_price
items.values.map{|i| i.total_price}.inject(0){|x,y|x+y}
end
end


Expand Down Expand Up @@ -52,5 +56,5 @@ class Signature
include XML::Mapping

text_node :name, "Name"
text_node :position, "Position"
text_node :position, "Position", :optional=>true, :default_value=>"Some Employee"
end
1 change: 0 additions & 1 deletion examples/order.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@

<Signed-By>
<Name>Miles O'Brien</Name>
<Position>packer</Position>
</Signed-By>
</Signatures>

Expand Down
50 changes: 49 additions & 1 deletion examples/order_usage.intin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,58 @@
$:.unshift "../lib"
require 'order' #<=
#:visible:
####read access
o=Order.load_from_file("order.xml") #<=
o.reference #<=
o.client #<=
o.signatures #<=
o.items.keys #<=
o.items["RF-0034"].descr #<=
o.items["RF-0034"].total_price #<=
o.signatures #<=
o.signatures[2].name #<=
o.signatures[2].position #<=
## default value was set

o.total_price #<=

####write access
o.client.name="James T. Kirk"
o.items['RF-4711'] = Item.new
o.items['RF-4711'].descr = 'power transfer grid'
o.items['RF-4711'].quantity = 2
o.items['RF-4711'].unit_price = 29.95

s=Signature.new
s.name='Harry Smith'
s.position='general manager'
o.signatures << s
xml=o.save_to_xml #convert to REXML node; there's also o.save_to_file(name) #<=
xml.write($stdout,2) #<=

####Starting a new order from scratch
o = Order.new #<=
## attributes with default values (here: signatures) are set
## automatically

#:handle_exceptions:
xml=o.save_to_xml #<=
#:no_exceptions:
## can't save as long as there are still unset attributes without
## default values

o.reference = "FOOBAR-1234"

o.client = Client.new
o.client.name = 'Ford Prefect'
o.client.address = Address.new
o.client.address.street = 'Park Av. 42'
o.client.address.city = 'small planet'
o.client.address.zip = 17263
o.client.address.state = 'Betelgeuse system'

o.items={'XY-42' => Item.new}
o.items['XY-42'].descr = 'improbability drive'
o.items['XY-42'].quantity = 3
o.items['XY-42'].unit_price = 299.95

o.save_to_xml.write($stdout,2) #<=

0 comments on commit 05f4470

Please sign in to comment.