Module: AssociateBy::ClassMethods

Defined in:
lib/associate_by.rb

Instance Method Summary collapse

Instance Method Details

#associate_by(association, method, options = {}) ⇒ Object



8
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
37
38
39
40
# File 'lib/associate_by.rb', line 8

def associate_by(association, method, options = {})
  attr_writer "#{association.to_s.singularize}_#{method}"

  define_method("#{association.to_s.singularize}_#{method}") do
    begin
      instance_variable_get("@#{association.to_s.singularize}_#{method}") || self.send("#{association.to_s}")[method]
    rescue
      ""
    end
  end
  
  define_method("#{association.to_s.singularize}_#{method}_create?", lambda { options[:create] || false} )

  define_method("before_save_for_#{association.to_s.singularize}_#{method}") do
    object = association.to_s.singularize.camelize.constantize.where(["#{method} = ?", self.send("#{association.to_s.singularize}_#{method}")]).first

    # If the object doesn't exist and the parameter create is true, then create it
    if object.nil? && self.send("#{association.to_s.singularize}_#{method}_create?")
      Rails.logger.info("AAAAAAAAAAAAAAAAAAAAAAAAAAAA")
      object = association.to_s.singularize.camelize.constantize.create({"#{method}" => self.send("#{association.to_s.singularize}_#{method}")})
    end

    if object
      if self.send("#{association.to_s}").is_a?(Array)
        self.send("#{association.to_s}") << object
      else
        self.send("#{association.to_s.singularize}=", object)
      end
    end
  end

  before_save "before_save_for_#{association.to_s.singularize}_#{method}"
end