Module: ComposableDecorator::ActiveRecord::DSL

Defined in:
lib/composable_decorator/active_record/dsl.rb

Instance Method Summary collapse

Instance Method Details

#__define_delegation(associations: [], prefix: true, allow_nil: true, handle_nil_with: '') ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/composable_decorator/active_record/dsl.rb', line 59

def __define_delegation(associations: [], prefix: true, allow_nil: true, handle_nil_with: '')
  existing_delegations = __delegations

  define_singleton_method(:__delegations) {
    [
      {
        associations: associations,
        prefix: prefix,
        allow_nil: allow_nil
      }
    ] + existing_delegations
  }
end

#__initializeObject



20
21
22
23
24
# File 'lib/composable_decorator/active_record/dsl.rb', line 20

def __initialize
  define_singleton_method(:__decorators) { [] }
  define_singleton_method(:__associations) { [] }
  define_singleton_method(:__delegations) { [] }
end

#decorate_with(*decorators) ⇒ Object

# declares the order of decorators applied to an instance # that calls the #decorate method

class AdminUser

decorate_with UserDecorator, AdminDecorator

# The above code results in #decorate first decorating the instance # with the UserDecorator, then the AdminDecorator



14
15
16
17
18
# File 'lib/composable_decorator/active_record/dsl.rb', line 14

def decorate_with(*decorators)
  existing_decorators = __decorators

  define_singleton_method(:__decorators) { decorators + existing_decorators }
end

#delegate_decorated_to(*associations, prefix: true, allow_nil: true, handle_nil_with: '') ⇒ Object

# delegates all of the decorated methods for each has_one or belongs_to association.

module PostDecorator

delegate_decorated_to :author

def full_name
  "#{name} {created_at}"

class Post

belongs_to :author
decorate_with PostDecorator

# The above code allows you to call:

post.decorate post.author_full_name

# Like Rails’s #delegate method, you can choose to allow_nil # or to prefix the delegated method. Both default to true.



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/composable_decorator/active_record/dsl.rb', line 47

def delegate_decorated_to(*associations, prefix: true, allow_nil: true, handle_nil_with: '')
  existing_associations = __associations

  __define_delegation(
    associations: associations,
    prefix: prefix,
    allow_nil: allow_nil,
    handle_nil_with: handle_nil_with)

  define_singleton_method(:__associations) { associations + existing_associations }
end