Skip to content

Instantly share code, notes, and snippets.

@apotonick
Last active December 16, 2015 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apotonick/5351023 to your computer and use it in GitHub Desktop.
Save apotonick/5351023 to your computer and use it in GitHub Desktop.
require 'ostruct'
require 'benchmark'
require 'representable/hash'
# --------- extend
module SongRepresenter
include Representable::Hash
property :name
property :length
property :track
end
module AlbumRepresenter
include Representable::Hash
collection :songs, extend: SongRepresenter
end
class Song
attr_accessor :name, :length, :track
def initialize(*options)
@name, @length, @track = *options
end
end
# --------- decorate
class SongRepresentation < Representable::Decorator
include Representable::Hash
include SongRepresenter
end
class AlbumRepresentation < Representable::Decorator
include Representable::Hash
collection :songs, decorator: SongRepresentation
end
for strategy, mod in [[:extend, AlbumRepresenter], [:decorate, AlbumRepresentation]]
album = OpenStruct.new(:songs => 10000.times.collect { Song.new("Marea", 3.14, "01") } )
time = Benchmark.measure do
album = Representable.prepare(album, mod, strategy)
album.to_hash
end
puts "time with #{strategy} : #{time}"
end
# time with extend : 0.780000 0.000000 0.780000 ( 0.783960)
# time with decorate : 0.600000 0.000000 0.600000 ( 0.601738)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment