Last active
August 29, 2015 14:16
-
-
Save jurre/cd26a4b769d97b3f7e3e to your computer and use it in GitHub Desktop.
Simple Collection Decorator that plays nice with Kaminari
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
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