Guest User

Untitled

a guest
Apr 24th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. ## Documents pattern helps to save memory & cpu time providing cheap OO interface for the arrays of raw data without need to instantiate a lot of objects.
  2.  
  3. class Documents
  4. include Enumerable
  5. def initialize(collection)
  6. @collection = collection
  7. @element = collection.first
  8. end
  9. def each
  10. @collection.each do |raw_element|
  11. @element = raw_element
  12. yield self
  13. end
  14. end
  15. end
  16.  
  17. # Regular class (object per element)
  18. class Video
  19. def actor
  20. @actor # instance data
  21. end
  22. end
  23.  
  24. # Wrapper for an array (one object for many elements)
  25. class Videos < Documents
  26. def actor
  27. @element["actor"] # raw data of the current element
  28. end
  29. end
  30.  
  31.  
  32. ## USAGE
  33.  
  34. # non-optimized:
  35.  
  36. raw_data = [{"actor" => "Arnold"}, {"actor" => "Charles"}, ...]
  37.  
  38. videos = raw_data.map{|r| Video.new(r) }
  39. videos.each do |video|
  40. # do something with video
  41. end
  42.  
  43. # optimized:
  44.  
  45. videos = Videos.new(raw_data)
  46. videos.each do |video|
  47. # do something with video (fake enumerator with the same interface as Video)
  48. end
Add Comment
Please, Sign In to add comment