Module: Cookbook::Mixins::ActsAsUseOf

Extended by:
ActiveSupport::Concern
Defined in:
lib/cookbook/mixins/acts_as_use_of.rb

Overview

ActsAsUseIn Mixin, for things like Recipes or HowTos

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Instance Method Summary collapse

Instance Method Details

#acts_as_use_of(*model_symbols) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/cookbook/mixins/acts_as_use_of.rb', line 9

def acts_as_use_of(*model_symbols)
  extend ClassMethods
  include InstanceMethods

  self.used_in = model_symbols
  Cookbook::Use.add_use_in(table_name.to_sym)

  # Relationships
  has_many :uses, as: :use_in, class_name: 'Cookbook::Use', inverse_of: :use_in
  # Used only as a setter, not a getter
  accepts_nested_attributes_for :uses, reject_if: :all_blank, allow_destroy: true
  associate_used_in

  used_in.each do |table_sym|
    singular = table_sym.to_s.singularize
    model = singular.classify.constantize
    equals_method_symbol = "#{singular}_uses_attributes=".to_sym
    define_method(equals_method_symbol) do |values|
      items = []
      values.each_pair do |key, value|
        value['use_in'] = self
        value['use_of'] = model.find_by(id: value['use_of_id'])
        items << value
      end
      self.uses_attributes = items
    end
  end
end