Class: DataMapper::Property::Discriminator

Inherits:
Class show all
Includes:
PassThroughLoadDump
Defined in:
lib/dm-core/property/discriminator.rb

Constant Summary

Constants inherited from DataMapper::Property

INVALID_NAMES, OPTIONS, PRIMITIVES, VISIBILITY_OPTIONS

Instance Attribute Summary

Attributes inherited from DataMapper::Property

#allow_blank, #allow_nil, #default, #index, #instance_variable_name, #model, #name, #options, #primitive, #reader_visibility, #repository_name, #required, #unique_index, #writer_visibility

Instance Method Summary collapse

Methods included from PassThroughLoadDump

#dump, #load

Methods inherited from Class

#typecast_to_primitive

Methods inherited from Object

#dump, #load, #to_child_key

Methods inherited from DataMapper::Property

accept_options, accepted_options, #allow_blank?, #allow_nil?, #assert_valid_options, demodulized_names, descendants, determine_class, #determine_visibility, #field, find_class, #get, #get!, inherited, #initialize, #inspect, #key?, #lazy?, #lazy_load, #lazy_load_properties, #loaded?, nullable, options, #primitive?, #properties, #required?, #serial?, #set, #set!, #typecast, #unique?, #valid?

Methods included from Chainable

#chainable, #extendable

Methods included from Equalizer

#equalize

Methods included from Deprecate

#deprecate

Methods included from Subject

#default?, #default_for

Methods included from Assertions

#assert_kind_of

Constructor Details

This class inherits a constructor from DataMapper::Property

Instance Method Details

#bindObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



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
41
42
43
44
45
# File 'lib/dm-core/property/discriminator.rb', line 10

def bind
  model.default_scope(repository_name).update(name => model.descendants.dup << model)

  model.class_eval <<-RUBY, __FILE__, __LINE__ + 1
    extend Chainable

    extendable do
      def inherited(model)
        super  # setup self.descendants
        set_discriminator_scope_for(model)
      end

      def new(*args, &block)
        if args.size == 1 && args.first.kind_of?(Hash)
          discriminator = properties(repository_name).discriminator

          if discriminator_value = args.first[discriminator.name]
            model = discriminator.typecast_to_primitive(discriminator_value)

            if model.kind_of?(Model) && !model.equal?(self)
              return model.new(*args, &block)
            end
          end
        end

        super
      end

      private

      def set_discriminator_scope_for(model)
        model.default_scope(#{repository_name.inspect}).update(#{name.inspect} => model.descendants.dup << model)
      end
    end
  RUBY
end