Class: ActiveDecorator::Decorator
- Inherits:
-
Object
- Object
- ActiveDecorator::Decorator
- Includes:
- Singleton
- Defined in:
- lib/active_decorator/decorator.rb
Instance Method Summary collapse
-
#decorate(obj) ⇒ Object
Decorates the given object.
-
#decorate_association(owner, target) ⇒ Object
Decorates AR model object’s association only when the object was decorated.
-
#initialize ⇒ Decorator
constructor
A new instance of Decorator.
Constructor Details
#initialize ⇒ Decorator
Returns a new instance of Decorator.
11 12 13 |
# File 'lib/active_decorator/decorator.rb', line 11 def initialize @@decorators = {} end |
Instance Method Details
#decorate(obj) ⇒ Object
Decorates the given object. Plus, performs special decoration for the classes below:
Array: decorates its each element
AR::Relation: decorates its each record lazily
AR model: decorates its associations on the fly
Always returns the object, regardless of whether decorated or not decorated.
This method can be publicly called from anywhere by ‘ActiveDecorator::Decorator.instance.decorate(obj)`.
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/active_decorator/decorator.rb', line 24 def decorate(obj) return if defined?(Jbuilder) && (Jbuilder === obj) return if obj.nil? if obj.is_a?(Array) obj.each do |r| decorate r end elsif defined?(ActiveRecord) && obj.is_a?(ActiveRecord::Relation) # don't call each nor to_a immediately if obj.respond_to?(:records) # Rails 5.0 obj.extend ActiveDecorator::RelationDecorator unless obj.is_a? ActiveDecorator::RelationDecorator else # Rails 3.x and 4.x obj.extend ActiveDecorator::RelationDecoratorLegacy unless obj.is_a? ActiveDecorator::RelationDecoratorLegacy end else if defined?(ActiveRecord) && obj.is_a?(ActiveRecord::Base) && !obj.is_a?(ActiveDecorator::Decorated) obj.extend ActiveDecorator::Decorated end d = decorator_for obj.class return obj unless d obj.extend d unless obj.is_a? d end obj end |
#decorate_association(owner, target) ⇒ Object
Decorates AR model object’s association only when the object was decorated. Returns the association instance.
56 57 58 |
# File 'lib/active_decorator/decorator.rb', line 56 def decorate_association(owner, target) owner.is_a?(ActiveDecorator::Decorated) ? decorate(target) : target end |