Skip to content

Instantly share code, notes, and snippets.

@senny
Created October 2, 2012 12:05
Show Gist options
  • Save senny/3818503 to your computer and use it in GitHub Desktop.
Save senny/3818503 to your computer and use it in GitHub Desktop.
Simple Decorator implementation for our projects
require 'delegate'
class BasicDecorator < SimpleDelegator
def self.decorate(objects)
case objects
when Array
objects.map { |object| new(object) }
when ActiveRecord::Relation, DecoratedListProxy, ActiveRecord::Associations::CollectionProxy
DecoratedListProxy.new(self, objects)
else
new(objects)
end
end
def eql?(other)
other.eql?(__getobj__)
end
def to_model
__getobj__
end
def class
__getobj__.class
end
class DecoratedListProxy < SimpleDelegator
def initialize(decorator_class, list)
super(list)
@decorator_class = decorator_class
end
def to_a(*args)
evaluate
end
def each(&block)
evaluate.each(&block)
end
def map(&block)
evaluate.map(&block)
end
def evaluate
@evaluated_objects ||= __getobj__.map do |object|
@decorator_class.new(object)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment