Class: ActiveDelegate::Delegator

Inherits:
Object
  • Object
show all
Defined in:
lib/active_delegate/delegator.rb

Overview

Validates delegation target and sets basic options

Direct Known Subclasses

Associations, Attributes

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, options) ⇒ Delegator

Returns a new instance of Delegator.



8
9
10
11
# File 'lib/active_delegate/delegator.rb', line 8

def initialize(model, options)
  @model   = model
  @options = default_options.merge(options.symbolize_keys)
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



6
7
8
# File 'lib/active_delegate/delegator.rb', line 6

def model
  @model
end

#optionsObject (readonly)

Returns the value of attribute options.



6
7
8
# File 'lib/active_delegate/delegator.rb', line 6

def options
  @options
end

Instance Method Details

#association_classObject



52
53
54
# File 'lib/active_delegate/delegator.rb', line 52

def association_class
  association_reflection.klass
end

#association_nameObject



41
42
43
# File 'lib/active_delegate/delegator.rb', line 41

def association_name
  @options[:to]
end

#association_reflectionObject



45
46
47
48
49
50
# File 'lib/active_delegate/delegator.rb', line 45

def association_reflection
  reflection = model.reflect_on_association(association_name)
  return reflection unless reflection.nil?

  raise "#{model.name} don't have the association #{association_name}"
end

#default_optionsObject



13
14
15
16
17
18
19
20
# File 'lib/active_delegate/delegator.rb', line 13

def default_options
  {
    except:    [],
    only:      [],
    to:        nil,
    allow_nil: false
  }
end

#delegation_args(available = []) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/active_delegate/delegator.rb', line 26

def delegation_args(available = [])
  included   = Array(options[:only]).map(&:to_sym)
  excluded   = Array(options[:except]).map(&:to_sym)
  available  = Array(available).map(&:to_sym)
  available &= included if included.any?
  available -= excluded if excluded.any?

  available
end

#delegation_optionsObject



22
23
24
# File 'lib/active_delegate/delegator.rb', line 22

def delegation_options
  options.select { |k, _v| k.in? %i[to allow_nil prefix] }
end

#delegation_prefixObject



36
37
38
39
# File 'lib/active_delegate/delegator.rb', line 36

def delegation_prefix
  prefix = options[:prefix]
  prefix == true ? association_name : prefix
end