Created
October 2, 2012 12:05
-
-
Save senny/3818503 to your computer and use it in GitHub Desktop.
Simple Decorator implementation for our projects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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