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



49
50
51
52
53
54
# File 'lib/composable_decorator/active_record/dsl.rb', line 49

def __define_delegation(associations: [], prefix: true, allow_nil: true, handle_nil_with: '')
  define_method(:__associations) { associations }
  define_method(:__prefix) { prefix }
  define_method(:__allow_nil) { allow_nil }
  define_method(:__handle_nil_with) { handle_nil_with }
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 = defined?(__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.



41
42
43
44
45
46
47
# File 'lib/composable_decorator/active_record/dsl.rb', line 41

def delegate_decorated_to(*associations, prefix: true, allow_nil: true, handle_nil_with: '')
  __define_delegation(
    associations: associations,
    prefix: prefix,
    allow_nil: allow_nil,
    handle_nil_with: handle_nil_with)
end