Module: Polymorpheus::Interface::ClassMethods

Defined in:
lib/polymorpheus/interface.rb

Instance Method Summary collapse

Instance Method Details

#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

#has_many_as_polymorph(association, options = {}) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/polymorpheus/interface.rb', line 63

def has_many_as_polymorph(association, options = {})
  options.symbolize_keys!
  conditions = options.fetch(:conditions, {})
  fkey = name.foreign_key

  class_name = options[:class_name] || association.to_s.classify

  options[:conditions] = proc {
    keys = class_name.constantize
            .const_get('POLYMORPHEUS_ASSOCIATIONS')
            .map(&:foreign_key)
    keys.delete(fkey)

    keys.reduce({}) { |hash, key| hash.merge!(key => nil) }
  }

  has_many association, options
end

#validates_polymorph(polymorphic_api) ⇒ Object



82
83
84
85
86
87
88
89
90
# File 'lib/polymorpheus/interface.rb', line 82

def validates_polymorph(polymorphic_api)
  validate Proc.new {
    unless polymorpheus.active_association
      association_names = polymorpheus.associations.map(&:name)
      errors.add(:base, "You must specify exactly one of the following: "\
                        "{#{association_names.join(', ')}}")
    end
  }
end