Sha256: 5cda5c2fe41743f0e22109dddf2bd652ea4ecca28d9a1008566c51375c12affa

Contents?: true

Size: 1.85 KB

Versions: 4

Compression:

Stored size: 1.85 KB

Contents

module Migrant
  module ModelExtensions
    attr_accessor :schema
    def structure(&block)
      # Using instance_*evil* to get the neater DSL on the models.
      # So, my_field in the structure block actually calls Migrant::Schema.my_field

      if self.superclass == ActiveRecord::Base
        @schema ||= Schema.new
        @schema.add_associations(self.reflect_on_all_associations)
        @schema.define_structure(&block)
        
        @schema.validations.each do |field, validation_options|
          validations = (validation_options.class == Array)? validation_options : [validation_options]
          validations.each do |validation|
            validation = (validation.class == Hash)? validation : { validation => true }
            self.validates(field, validation)
          end
        end
      else
        self.superclass.structure(&block) # For STI, cascade all fields onto the parent model
        @schema = InheritedSchema.new(self.superclass.schema)
      end
    end

    # Same as defining a structure block, but with no attributes besides
    # relationships (such as in a many-to-many)
    def no_structure
      structure {}
    end

    def mock(attributes={}, recursive=true)
      attribs = @schema.columns.reject { |column| column.is_a?(DataType::ForeignKey)}.collect { |name, data_type| [name, data_type.mock] }.flatten

      # Only recurse to one level, otherwise things get way too complicated
      if recursive
        attribs += self.reflect_on_all_associations(:belongs_to).collect do |association|
                    begin
                      (association.klass.respond_to?(:mock))? [association.name, association.klass.mock({}, false)] : nil
                    rescue NameError; nil; end # User hasn't defined association, just skip it
                   end.compact.flatten
      end
      new Hash[*attribs].merge(attributes)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
migrant-1.0.2 lib/migrant/model_extensions.rb
migrant-1.0.1 lib/migrant/model_extensions.rb
migrant-1.0.0 lib/migrant/model_extensions.rb
migrant-0.2.4 lib/migrant/model_extensions.rb