Skip to content

Instantly share code, notes, and snippets.

@timurvafin
Last active August 29, 2015 14:20
Show Gist options
  • Save timurvafin/502b46ad3ed47ae6fb4e to your computer and use it in GitHub Desktop.
Save timurvafin/502b46ad3ed47ae6fb4e to your computer and use it in GitHub Desktop.
Presenters
class CollectionPresenter
include Enumerable
delegate :current_page, :total_pages, :limit_value, :entry_name, :total_count,
:offset_value, :last_page?, to: :@collection
cattr_accessor :presenter
self.presenter = ModelPresenter
def initialize(collection)
@collection = collection
end
def each(*args, &block)
@collection.each { |item| yield(presenter.new(item)) }
end
end
class ModelPresenter
delegate :to_model, :to_key, :to_param, :to_partial_path, to: :@record
def initialize(record)
@record = record
end
end
class UserPresenter < ModelPresenter
delegate :email, :full_name, to: :@record
def full_name_with_email
"#{@record.full_name} (#{@record.email})"
end
end
class UsersPresenter < CollectionPresenter
self.presenter = UserPresenter
def avarage_something
@collection.sum(:id) / @collection.size
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment