项目作者: pdabrowski6

项目描述 :
A pure implementation of the decorator pattern
高级语言: Ruby
项目地址: git://github.com/pdabrowski6/tuner.git
创建时间: 2019-04-12T14:01:33Z
项目社区:https://github.com/pdabrowski6/tuner

开源协议:

下载


Tuner

A pure implementation of decorator pattern, alternative to Draper gem

Installation

  1. gem install tuner

Usage

Turn your class into decorator by inheriting from Tuner::Decorator class:

  1. class UserDecorator < Tuner::Decorator
  2. def full_name
  3. "#{model.first_name} #{model.last_name}"
  4. end
  5. end

then you can decorate your object:

  1. user = User.find(...)
  2. UserDecorator.new(user)
  3. # or
  4. UserDecorator.decorate(user)

Benchmarks

In basic usage, Tuner is around 3 times faster than Draper and it allocates 60% less objects.

Code used for benchmarks:

  1. require 'allocation_stats'
  2. require 'draper'
  3. require 'tuner'
  4. require 'benchmark'
  5. class UserTunerDecorator < Tuner::Decorator
  6. def full_name
  7. "#{model.first_name} #{model.last_name}"
  8. end
  9. end
  10. class UserDraperDecorator < Draper::Decorator
  11. def full_name
  12. "#{model.first_name} #{model.last_name}"
  13. end
  14. end
  15. user = Struct.new(:first_name, :last_name).new('John', 'Doe')
  16. stats = AllocationStats.trace { UserDraperDecorator.new(user).full_name }
  17. puts stats.allocations.group_by(:class).to_text
  18. stats = AllocationStats.trace { UserTunerDecorator.new(user).full_name }
  19. puts stats.allocations.group_by(:class).to_text
  20. Benchmark.bm 10 do |bench|
  21. bench.report "Tuner: " do
  22. 1_000_000.times { UserTunerDecorator.new(user).full_name }
  23. end
  24. bench.report "Draper: " do
  25. 1_000_000.times { UserDraperDecorator.new(user).full_name }
  26. end
  27. end