Module: Subroutine::Association

Defined in:
lib/subroutine/association.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/subroutine/association.rb', line 5

def self.included(base)
  base.send :extend, ::Subroutine::Association::ClassMethods
  class << base
    alias_method :field_without_associations, :field
    alias_method :field, :field_with_associations
  end

  base.send(:alias_method, :setup_fields_without_association, :setup_fields)
  base.send(:alias_method, :setup_fields, :setup_fields_with_association)
end

Instance Method Details

#polymorphic_instance(_type, _id, _unscoped = false) ⇒ Object



120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/subroutine/association.rb', line 120

def polymorphic_instance(_type, _id, _unscoped = false)
  return nil unless _type && _id

  klass = _type
  klass = klass.classify.constantize if klass.is_a?(String)

  return nil unless klass

  scope = klass.all
  scope = scope.unscoped if _unscoped

  scope.find(_id)
end

#setup_fields_with_association(*args) ⇒ Object



109
110
111
112
113
114
115
116
117
118
# File 'lib/subroutine/association.rb', line 109

def setup_fields_with_association(*args)
  setup_fields_without_association(*args)

  _fields.each_pair do |field, config|
    next unless config[:association]
    next unless @original_params.key?(field)

    send("#{field}=", @original_params[field]) # this gets the _id and _type into the params hash
  end
end