Sha256: 1063f342e6e325654e3bb13e9f00b6149a6fe6b2456782230d4b21bb84efb807

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

# Minimal example of a decorator
require_dependency 'post'

# DelegateClass(Post) does not delegate attribute methods
# in some environments:
# http://travis-ci.org/#!/gregbell/active_admin/jobs/2021466
#
class PostDecorator < SimpleDelegator
  delegate :id, :to => :__getobj__

  def self.decorate(collection_or_object)
    if collection_or_object.respond_to?(:to_ary)
      DecoratedEnumerableProxy.new(collection_or_object)
    else
      new(collection_or_object)
    end
  end

  def self.model_name
    ActiveModel::Name.new Post
  end

  def decorator_method
    'A method only available on the decorator'
  end

  # Minimal example of decorating a collection.
  # A full example can be found in the draper project:
  # https://github.com/jcasimir/draper/blob/master/lib/draper/decorated_enumerable_proxy.rb
  class DecoratedEnumerableProxy < DelegateClass(ActiveRecord::Relation)
    include Enumerable

    delegate :as_json, :collect, :map, :each, :[], :all?, :include?, :first, :last, :shift, :to => :decorated_collection

    def klass
      PostDecorator
    end

    def wrapped_collection
      __getobj__
    end

    def decorated_collection
      @decorated_collection ||= wrapped_collection.collect { |member| klass.decorate(member) }
    end
    alias_method :to_ary, :decorated_collection

    def each(&blk)
      to_ary.each(&blk)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activeadmin-0.5.1 spec/support/templates/post_decorator.rb