Method: Polymorpheus::Interface::ClassMethods#belongs_to_polymorphic

Defined in:
lib/polymorpheus/interface.rb

#belongs_to_polymorphic(*association_names, options) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/polymorpheus/interface.rb', line 25

def belongs_to_polymorphic(*association_names, options)
  polymorphic_api = options[:as]
  builder = Polymorpheus::InterfaceBuilder.new(polymorphic_api,
                                               association_names)

  # The POLYMORPHEUS_ASSOCIATIONS constant is useful for two reasons:
  #
  # 1. It is useful for other classes to be able to ask this class
  #    about its polymorphic relationship.
  #
  # 2. It prevents a class from defining multiple polymorphic
  #    relationships. Doing so would be a bad idea from a design
  #    standpoint, and we don't want to allow for (and support)
  #    that added complexity.
  #
  const_set('POLYMORPHEUS_ASSOCIATIONS', builder.association_names)

  # Set belongs_to associations
  builder.associations.each do |association|
    belongs_to association.name.to_sym
  end

  # Exposed interface for introspection
  define_method 'polymorpheus' do
    builder.exposed_interface(self)
  end

  # Getter method
  define_method polymorphic_api do
    builder.get_associated_object(self)
  end

  # Setter method
  define_method "#{polymorphic_api}=" do |object_to_associate|
    builder.set_associated_object(self, object_to_associate)
  end
end