Module: Sandwich::Helpers::Associations

Defined in:
lib/sandwich/helpers/associations.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/sandwich/helpers/associations.rb', line 4

def method_missing(name, *args)
  plural_name = name.to_s.gsub('=', '').pluralize

  if respond_to?(plural_name)
    value       = args.first
    association = self.class.reflect_on_association(plural_name.to_sym)
    
    if association
      child_class = association.class_name.constantize

      if value.kind_of?(child_class)
        send(association_name) << value
      else
        send(plural_name) << 
          child_class.find_or_make(child_class.default_attribute_query(value))
      end
    else
      if send(plural_name)
        send(plural_name) << value
      else
        send("#{plural_name}=", [value])
      end
    end
  else
    super
  end
end