nokogiri-happymapper 0.3.6 → 0.5.1

Sign up to get free protection for your applications and to get access to all the features.
data/README.md ADDED
@@ -0,0 +1,521 @@
1
+ HappyMapper
2
+ ===========
3
+
4
+ Happymapper allows you to parse XML data and convert it quickly and easily into ruby data structures.
5
+
6
+ This project is a fork of the great work done first by
7
+ [jnunemaker](https://github.com/jnunemaker/happymapper).
8
+
9
+ ## Major Differences
10
+
11
+ * [Nokogiri](http://nokogiri.org/) support
12
+ * Text nodes parsing
13
+ * Raw XML content parsing
14
+ * [burtlo](http://github.com/burtlo/happymapper)'s `#to_xml` support utilizing the same HappyMapper tags
15
+ * Fixes for [namespaces when using composition of classes](https://github.com/burtlo/happymapper/commit/fd1e898c70f7289d2d2618d629b56f2f6623785c)
16
+ * Fixes for instances of XML where a [namespace is defined but no elements with that namespace are found](https://github.com/burtlo/happymapper/commit/9614221a80ff3bda18ff859aa751dff29cf52fd3).
17
+
18
+ ## Installation
19
+
20
+ ### [Rubygems](https://rubygems.org/gems/nokogiri-happymapper)
21
+
22
+ $ gem install nokogiri-happymapper
23
+
24
+ ### [Bundler](http://gembundler.com/)
25
+ Add the unhappymapper gem to your project's `Gemfile`.
26
+
27
+ gem 'nokogiri-happymapper', :require => 'happymapper'
28
+
29
+ Run the bundler command to install the gem:
30
+
31
+ $ bundle install
32
+
33
+ # Examples
34
+
35
+ Let's start with a simple example to get our feet wet. Here we have a simple example of XML that defines some address information:
36
+
37
+ <address>
38
+ <street>Milchstrasse</street>
39
+ <housenumber>23</housenumber>
40
+ <postcode>26131</postcode>
41
+ <city>Oldenburg</city>
42
+ <country code="de">Germany</country>
43
+ </address>
44
+
45
+ Happymapper will let you easily model this information as a class:
46
+
47
+ require 'happymapper'
48
+
49
+ class Address
50
+ include HappyMapper
51
+
52
+ tag 'address'
53
+ element :street, String, :tag => 'street'
54
+ element :postcode, String, :tag => 'postcode'
55
+ element :housenumber, Integer, :tag => 'housenumber'
56
+ element :city, String, :tag => 'city'
57
+ element :country, String, :tag => 'country'
58
+ end
59
+
60
+ To make a class HappyMapper compatible you simply `include HappyMapper` within the class definition. This takes care of all the work of defining all the speciality methods and magic you need to get running. As you can see we immediately start using these methods.
61
+
62
+ * `tag` matches the name of the XML tag name 'address'.
63
+
64
+ * `element` defines accessor methods for the specified symbol (e.g. `:street`,`:housenumber`) that will return the class type (e.g. `String`,`Integer`) of the XML tag specified (e.g. `:tag => 'street'`, `:tag => 'housenumber'`).
65
+
66
+ When you define an element with an accessor with the same name as the tag, this is the case for all the examples above, you can omit the `:tag`. These two element declaration are equivalent to each other:
67
+
68
+ element :street, String, :tag => 'street'
69
+ element :street, String
70
+
71
+ Including the additional tag element is not going to hurt anything and in some cases will make it absolutely clear how these elements map to the XML. However, once you know this rule, it is hard not to want to save yourself the keystrokes.
72
+
73
+ Instead of `element` you may also use `has_one`:
74
+
75
+ element :street, String, :tag => 'street'
76
+ element :street, String
77
+ has_one :street, String
78
+
79
+ These three statements are equivalent to each other.
80
+
81
+ ## Parsing
82
+
83
+ With the mapping of the address XML articulated in our Address class it is time to parse the data:
84
+
85
+ address = Address.parse(ADDRESS_XML_DATA, :single => true)
86
+ puts address.street
87
+
88
+ Assuming that the constant `ADDRESS_XML_DATA` contains a string representation of the address XML data this is fairly straight-forward save for the `parse` method.
89
+
90
+ The `parse` method, like `tag` and `element` are all added when you included HappyMapper in the class. Parse is a wonderful, magical place that converts all these declarations that you have made into the data structure you are about to know and love.
91
+
92
+ But what about the `:single => true`? Right, that is because by default when your object is all done parsing it will be an array. In this case an array with one element, but an array none the less. So the following are equivalent to each other:
93
+
94
+ address = Address.parse(ADDRESS_XML_DATA).first
95
+ address = Address.parse(ADDRESS_XML_DATA, :single => true)
96
+
97
+ The first one returns an array and we return the first instance, the second will do that work for us inside of parse.
98
+
99
+ ## Multiple Elements Mapping
100
+
101
+ What if our address XML was a little different, perhaps we allowed multiple streets:
102
+
103
+ <address>
104
+ <street>Milchstrasse</street>
105
+ <street>Another Street</street>
106
+ <housenumber>23</housenumber>
107
+ <postcode>26131</postcode>
108
+ <city>Oldenburg</city>
109
+ <country code="de">Germany</country>
110
+ </address>
111
+
112
+ Similar to `element` or `has_one`, the declaration for when you have multiple elements you simply use:
113
+
114
+ has_many :streets, String, :tag => 'street'
115
+
116
+ Your resulting `streets` method will now return an array.
117
+
118
+ address = Address.parse(ADDRESS_XML_DATA, :single => true)
119
+ puts address.streets.join('\n')
120
+
121
+ Imagine that you have to write `streets.join('\n')` for the rest of eternity throughout your code. It would be a nightmare and one that you could avoid by creating your own convenience method.
122
+
123
+ require 'happymapper'
124
+
125
+ class Address
126
+ include HappyMapper
127
+
128
+ tag 'address'
129
+
130
+ has_many :streets, String
131
+
132
+ def streets
133
+ @streets.join('\n')
134
+ end
135
+
136
+ element :postcode, String, :tag => 'postcode'
137
+ element :housenumber, String, :tag => 'housenumber'
138
+ element :city, String, :tag => 'city'
139
+ element :country, String, :tag => 'country'
140
+ end
141
+
142
+ Now when we call the method `streets` we get a single value, but we still have the instance variable `@streets` if we ever need to the values as an array.
143
+
144
+
145
+ ## Attribute Mapping
146
+
147
+ <address location='home'>
148
+ <street>Milchstrasse</street>
149
+ <street>Another Street</street>
150
+ <housenumber>23</housenumber>
151
+ <postcode>26131</postcode>
152
+ <city>Oldenburg</city>
153
+ <country code="de">Germany</country>
154
+ </address>
155
+
156
+ Attributes are absolutely the same as `element` or `has_many`
157
+
158
+ attribute :location, String, :tag => 'location
159
+
160
+ Again, you can omit the tag if the attribute accessor symbol matches the name of the attribute.
161
+
162
+
163
+ ### Attributes On Empty Child Elements
164
+
165
+ <feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
166
+ <id>tag:all-the-episodes.heroku.com,2005:/tv_shows</id>
167
+ <link rel="alternate" type="text/html" href="http://all-the-episodes.heroku.com"/>
168
+ <link rel="self" type="application/atom+xml" href="http://all-the-episodes.heroku.com/tv_shows.atom"/>
169
+ <title>TV Shows</title>
170
+ <updated>2011-07-10T06:52:27Z</updated>
171
+ </feed>
172
+
173
+ In this case you would need to map an element to a new `Link` class just to access `<link>`s attributes, except that there is an alternate syntax. Instead of
174
+
175
+ class Feed
176
+ # ....
177
+ has_many :links, Link, :tag => 'link', :xpath => '.'
178
+ end
179
+
180
+ class Link
181
+ include HappyMapper
182
+
183
+ attribute :rel, String
184
+ attribute :type, String
185
+ attribute :href, String
186
+ end
187
+
188
+ You can drop the `Link` class and simply replace the `has_many` on `Feed` with
189
+
190
+ element :link, String, :single => false, :attributes => { :rel => String, :type => String, :href => String }
191
+
192
+ As there is no content, the type given for `:link` (`String` above) is irrelevant, but `nil` won't work and other types may try to perform typecasting and fail. You can omit the :single => false for elements that only occur once within their parent.
193
+
194
+ This syntax is most appropriate for elements that (a) have attributes but no content and (b) only occur at only one level of the heirarchy. If `<feed>` contained another element that also contained a `<link>` (as atom feeds generally do) it would be DRY-er to use the first syntax, i.e. with a separate `Link` class.
195
+
196
+
197
+ ## Class composition (and Text Node)
198
+
199
+ Our address has a country and that country element has a code. Up until this point we neglected it as we declared a `country` as being a `String`.
200
+
201
+ <address location='home'>
202
+ <street>Milchstrasse</street>
203
+ <street>Another Street</street>
204
+ <housenumber>23</housenumber>
205
+ <postcode>26131</postcode>
206
+ <city>Oldenburg</city>
207
+ <country code="de">Germany</country>
208
+ </address>
209
+
210
+ Well if we only going to parse country, on it's own, we would likely create a class mapping for it.
211
+
212
+ class Country
213
+ include HappyMapper
214
+
215
+ tag 'country'
216
+
217
+ attribute :code, String
218
+ content :name, String
219
+ end
220
+
221
+ We are utilizing an `attribute` declaration and a new declaration called `content`.
222
+
223
+ * `content` is used when you want the text contained within the element
224
+
225
+ Awesome, now if we were to redeclare our `Address` class we would use our new `Country` class.
226
+
227
+ class Address
228
+ include HappyMapper
229
+
230
+ tag 'address'
231
+
232
+ has_many :streets, String, :tag => 'street'
233
+
234
+ def streets
235
+ @streets.join('\n')
236
+ end
237
+
238
+ element :postcode, String, :tag => 'postcode'
239
+ element :housenumber, String, :tag => 'housenumber'
240
+ element :city, String, :tag => 'city'
241
+ element :country, Country, :tag => 'country'
242
+ end
243
+
244
+ Instead of `String`, `Boolean`, or `Integer` we say that it is a `Country` and HappyMapper takes care of the details of continuing the XML mapping through the country element.
245
+
246
+ address = Address.parse(ADDRESS_XML_DATA, :single => true)
247
+ puts address.country.code
248
+
249
+ A quick note, in the above example we used the constant `Country`. We could have used `'Country'`. The nice part of using the latter declaration, enclosed in quotes, is that you do not have to define your class before this class. So Country and Address can live in separate files and as long as both constants are available when it comes time to parse you are golden.
250
+
251
+ ## Custom XPATH
252
+
253
+ ### Has One, Has Many
254
+
255
+ Getting to elements deep down within your XML can be a little more work if you did not have xpath support. Consider the following example:
256
+
257
+ <media>
258
+ <gallery>
259
+ <title href="htttp://fishlovers.org/friends">Friends Who Like Fish</title>
260
+ <picture>
261
+ <name>Burtie Sanchez</name>
262
+ <img>burtie01.png</img>
263
+ </picture>
264
+ </gallery>
265
+ <picture>
266
+ <name>Unsorted Photo</name>
267
+ <img>bestfriends.png</img>
268
+ </picture>
269
+ </media>
270
+
271
+ You may want to map the sub-elements contained buried in the 'gallery' as top level items in the media. Traditionally you could use class composition to accomplish this task, however, using the xpath attribute you have the ability to shortcut some of that work.
272
+
273
+ class Media
274
+ include HappyMapper
275
+
276
+ has_one :title, String, :xpath => 'gallery/title'
277
+ has_one :link, String, :xpath => 'gallery/title/@href'
278
+ end
279
+
280
+
281
+ ## Subclasses
282
+
283
+ ### Inheritance (it doesn't work!)
284
+
285
+ While mapping XML to objects you may arrive at a point where you have two or more very similar structures.
286
+
287
+ class Article
288
+ include HappyMapper
289
+
290
+ has_one :title, String
291
+ has_one :author, String
292
+ has_one :published, Time
293
+
294
+ has_one :entry, String
295
+
296
+ end
297
+
298
+ class Gallery
299
+ include HappyMapper
300
+
301
+ has_one :title, String
302
+ has_one :author, String
303
+ has_one :published, Time
304
+
305
+ has_many :photos, String
306
+
307
+ end
308
+
309
+ In this example there are definitely two similarities between our two pieces of content. So much so that you might be included to create an inheritance structure to save yourself some keystrokes.
310
+
311
+ class Content
312
+ include HappyMapper
313
+
314
+ has_one :title, String
315
+ has_one :author, String
316
+ has_one :published, Time
317
+
318
+ end
319
+
320
+ class Article < Content
321
+ include HappyMapper
322
+
323
+ has_one :entry, String
324
+ end
325
+
326
+ class Gallery < Content
327
+ include HappyMapper
328
+
329
+ has_many :photos, String
330
+ end
331
+
332
+ However, *this does not work*. And the reason is because each one of these element declarations are method calls that are defining elements on the class itself. So it is not passed down through inheritance.
333
+
334
+ You can however, use some module mixin power to save you those keystrokes and impress your friends.
335
+
336
+
337
+ module Content
338
+ def self.included(content)
339
+ content.has_one :title, String
340
+ content.has_one :author, String
341
+ content.has_one :published, Time
342
+ end
343
+
344
+ def published_time
345
+ @published.strftime("%H:%M:%S")
346
+ end
347
+
348
+ end
349
+
350
+ class Article
351
+ include HappyMapper
352
+
353
+ include Content
354
+ has_one :entry, String
355
+ end
356
+
357
+ class Gallery
358
+ include HappyMapper
359
+
360
+ include Content
361
+ has_many :photos, String
362
+ end
363
+
364
+
365
+ Here, when we include `Content` in both of these classes the module method `#included` is called and our class is given as a parameter. So we take that opportunity to do some surgery and define our happymapper elements as well as any other methods that may rely on those instance variables that come along in the package.
366
+
367
+
368
+ ## Filtering with XPATH
369
+
370
+ I ran into a case where I wanted to capture all the pictures that were directly under media, but not the ones contained within a gallery.
371
+
372
+ <media>
373
+ <gallery>
374
+ <picture>
375
+ <name>Burtie Sanchez</name>
376
+ <img>burtie01.png</img>
377
+ </picture>
378
+ </gallery>
379
+ <picture>
380
+ <name>Unsorted Photo</name>
381
+ <img>bestfriends.png</img>
382
+ </picture>
383
+ </media>
384
+
385
+ The following `Media` class is where I started:
386
+
387
+ require 'happymapper'
388
+
389
+ class Media
390
+ include HappyMapper
391
+
392
+ has_many :galleries, Gallery, :tag => 'gallery'
393
+ has_many :pictures, Picture, :tag => 'picture'
394
+ end
395
+
396
+ However when I parsed the media xml the number of pictures returned to me was 2, not 1.
397
+
398
+ pictures = Media.parse(MEDIA_XML,:single => true).pictures
399
+ pictures.length.should == 1 # => Failed Expectation
400
+
401
+ I was mistaken and that is because, by default the mappings are assigned XPATH './/' which is requiring all the elements no matter where they can be found. To override this you can specify an XPATH value for your defined elements.
402
+
403
+ has_many :pictures, Picture, :tag => 'picture', :xpath => '/media'
404
+
405
+ `/media` states that we are only interested in pictures that can be found directly under the media element. So when we parse again we will have only our one element.
406
+
407
+
408
+ ## Namespaces
409
+
410
+ Obviously your XML and these trivial examples are easy to map and parse because they lack the treacherous namespaces that befall most XML files.
411
+
412
+ Perhaps our `address` XML is really swarming with namespaces:
413
+
414
+ <prefix:address location='home' xmlns:prefix="http://www.unicornland.com/prefix">
415
+ <prefix:street>Milchstrasse</prefix:street>
416
+ <prefix:street>Another Street</prefix:street>
417
+ <prefix:housenumber>23</prefix:housenumber>
418
+ <prefix:postcode>26131</prefix:postcode>
419
+ <prefix:city>Oldenburg</prefix:city>
420
+ <prefix:country code="de">Germany</prefix:country>
421
+ </prefix:address>
422
+
423
+ Here again is our address example with a made up namespace called `prefix` that comes direct to use from unicornland, a very magical place indeed. Well we are going to have to do some work on our class definition and that simply adding this one liner to the `Address` class:
424
+
425
+ class Address
426
+ include HappyMapper
427
+
428
+ tag 'address'
429
+ namespace 'prefix'
430
+ # ... rest of the code ...
431
+ end
432
+
433
+ Of course, if that is too easy for you, you can append a `:namespace => 'prefix` to every one of the elements that you defined.
434
+
435
+ has_many :street, String, :tag => 'street', :namespace => 'prefix'
436
+ element :postcode, String, :tag => 'postcode', :namespace => 'prefix'
437
+ element :housenumber, String, :tag => 'housenumber', :namespace => 'prefix'
438
+ element :city, String, :tag => 'city', :namespace => 'prefix'
439
+ element :country, Country, :tag => 'country', :namespace => 'prefix'
440
+
441
+ I definitely recommend the former, as it saves you a whole hell of lot of typing. However, there are times when appending a namespace to an element declaration is important and that is when it has a different namespace then `namespsace 'prefix'`.
442
+
443
+ Imagine that our `country` actually belonged to a completely different namespace.
444
+
445
+ <prefix:address location='home' xmlns:prefix="http://www.unicornland.com/prefix"
446
+ xmlns:prefix="http://www.trollcountry.com/different">
447
+ <prefix:street>Milchstrasse</prefix:street>
448
+ <prefix:street>Another Street</prefix:street>
449
+ <prefix:housenumber>23</prefix:housenumber>
450
+ <prefix:postcode>26131</prefix:postcode>
451
+ <prefix:city>Oldenburg</prefix:city>
452
+ <different:country code="de">Germany</different:country>
453
+ </prefix:address>
454
+
455
+ Well we would need to specify that namespace:
456
+
457
+ element :country, Country, :tag => 'country', :namespace => 'different'
458
+
459
+ With that we should be able to parse as we once did.
460
+
461
+ ## Large Datasets (in_groups_of)
462
+
463
+ When dealing with large sets of XML that simply cannot or should not be placed into memory the objects can be handled in groups through the `:in_groups_of` parameter.
464
+
465
+ Address.parse(LARGE_ADDRESS_XML_DATA,:in_groups_of => 5) do |group|
466
+ puts address.streets
467
+ end
468
+
469
+ This trivial block will parse the large set of XML data and in groups of 5 addresses at a time display the streets.
470
+
471
+ ## Saving to XML
472
+
473
+ Saving a class to XML is as easy as calling `#to_xml`. The end result will be the current state of your object represented as xml. Let's cover some details that are sometimes necessary and features present to make your life easier.
474
+
475
+
476
+ ### :on_save
477
+
478
+ When you are saving data to xml it is often important to change or manipulate data to a particular format. For example, a time object:
479
+
480
+ has_one :published_time, Time, :on_save => lambda {|time| time.strftime("%H:%M:%S") if time }
481
+
482
+ Here we add the options `:on_save` and specify a lambda which will be executed on the method call to `:published_time`.
483
+
484
+ ### :state_when_nil
485
+
486
+ When an element contains a nil value, or perhaps the result of the :on_save lambda correctly results in a nil value you will be happy that the element will not appear in the resulting XML. However, there are time when you will want to see that element and that's when `:state_when_nil` is there for you.
487
+
488
+ has_one :favorite_color, String, :state_when_nil => true
489
+
490
+ The resulting XML will include the 'favorite_color' element even if the favorite color has not been specified.
491
+
492
+ ### :read_only
493
+
494
+ When an element, attribute, or text node is a value that you have no interest in
495
+ saving to XML, you can ensure that takes place by stating that it is `read only`.
496
+
497
+ has_one :modified, Boolean, :read_only => true
498
+ attribute :temporary, Boolean, :read_only => true
499
+
500
+ This is useful if perhaps the incoming XML is different than the out-going XML.
501
+
502
+ ### namespaces
503
+
504
+ While parsing the XML only required you to simply specify the prefix of the namespace you wanted to parse, when you persist to xml you will need to define your namespaces so that they are correctly captured.
505
+
506
+ class Address
507
+ include HappyMapper
508
+
509
+ register_namespace 'prefix', 'http://www.unicornland.com/prefix'
510
+ register_namespace 'different', 'http://www.trollcountry.com/different'
511
+
512
+ tag 'address'
513
+ namespace 'prefix'
514
+
515
+ has_many :street, String
516
+ element :postcode, String
517
+ element :housenumber, String
518
+ element :city, String
519
+ element :country, Country, :tag => 'country', :namespace => 'different'
520
+
521
+ end