Skip to content

Instantly share code, notes, and snippets.

@jurre
Last active August 29, 2015 14:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jurre/cd26a4b769d97b3f7e3e to your computer and use it in GitHub Desktop.
Save jurre/cd26a4b769d97b3f7e3e to your computer and use it in GitHub Desktop.
Simple Collection Decorator that plays nice with Kaminari
class BaseDecorator
def initialize(source)
@source = source
end
def method_missing(method_key, *args, &block)
@source.send(method_key, *args, &block)
end
def respond_to_missing?(method_key, *args, &block)
@source.respond_to?(method_key, *args, &block)
end
end
class BaseDecorator::Collection
attr_accessor :source
array_methods = Array.instance_methods - Object.instance_methods
delegate :==, :as_json, *array_methods, to: :decorated_collection
delegate :current_page, :total_pages, :limit_value, to: :source
def initialize(source, page=nil)
@source = source.page(page)
end
def decorated_collection
@decorated_collection ||= source.map { |item| item_decorator(item).new(item) }
end
def item_decorator(obj)
"#{obj.class.name}Decorator".constantize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment