Class: ActiveAny::Associations::Builder::Association

Inherits:
Object
  • Object
show all
Defined in:
lib/active_any/associations/builder/association.rb

Constant Summary collapse

VALID_OPTIONS =
%i[class_name foreign_key].freeze

Class Method Summary collapse

Class Method Details

.build(klass, name, scope, options) ⇒ Object



7
8
9
10
11
12
# File 'lib/active_any/associations/builder/association.rb', line 7

def self.build(klass, name, scope, options)
  reflection = create_reflection(klass, name, scope, options)
  define_writer_method klass, reflection.name
  define_reader_method klass, reflection.name
  reflection
end

.build_scope(scope) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/active_any/associations/builder/association.rb', line 36

def self.build_scope(scope)
  new_scope = scope

  new_scope = proc { instance_exec(&scope) } if scope && scope.arity.zero?

  new_scope
end

.create_reflection(klass, name, scope, options) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/active_any/associations/builder/association.rb', line 24

def self.create_reflection(klass, name, scope, options)
  if scope.is_a?(::Hash)
    options = scope
    scope   = nil
  end

  validate_options(options)
  scope = build_scope scope

  ActiveAny::Reflection.create(macro, name, scope, options, klass)
end

.define_reader_method(klass, name) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/active_any/associations/builder/association.rb', line 44

def self.define_reader_method(klass, name)
  klass.class_eval <<-CODE, __FILE__, __LINE__ + 1
    def #{name}(*args)
      association(:#{name}).reader(*args)
    end
  CODE
end

.define_writer_method(klass, name) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/active_any/associations/builder/association.rb', line 52

def self.define_writer_method(klass, name)
  klass.class_eval <<-CODE, __FILE__, __LINE__ + 1
    def #{name}=(value)
      association(:#{name}).writer(value)
    end
  CODE
end

.valid_optionsObject



16
17
18
# File 'lib/active_any/associations/builder/association.rb', line 16

def self.valid_options
  VALID_OPTIONS
end

.validate_options(options) ⇒ Object



20
21
22
# File 'lib/active_any/associations/builder/association.rb', line 20

def self.validate_options(options)
  options.assert_valid_keys(valid_options)
end