Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## 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.
- class Documents
- include Enumerable
- def initialize(collection)
- @collection = collection
- @element = collection.first
- end
- def each
- @collection.each do |raw_element|
- @element = raw_element
- yield self
- end
- end
- end
- # Regular class (object per element)
- class Video
- def actor
- @actor # instance data
- end
- end
- # Wrapper for an array (one object for many elements)
- class Videos < Documents
- def actor
- @element["actor"] # raw data of the current element
- end
- end
- ## USAGE
- # non-optimized:
- raw_data = [{"actor" => "Arnold"}, {"actor" => "Charles"}, ...]
- videos = raw_data.map{|r| Video.new(r) }
- videos.each do |video|
- # do something with video
- end
- # optimized:
- videos = Videos.new(raw_data)
- videos.each do |video|
- # do something with video (fake enumerator with the same interface as Video)
- end
Add Comment
Please, Sign In to add comment