Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does DataMapper use mixins vs inheritance?

So I'm just curious about this:

DataMapper uses a mixin for its Models

class Post
  include DataMapper::Resource

While active-record uses inheritance

class Post < ActiveRecord::Base

Does anyone know why DataMapper chose to do it that way (or why AR chose not to)?

like image 461
cloudhead Avatar asked Jul 24 '09 21:07

cloudhead


1 Answers

It lets you inherit from another class that isn't a DM class.

It also allows adding the DM features to a class on the fly. Here's a class method from a module I'm working on right now:

def datamapper_class
  klass = self.dup
  klass.send(:include, DataMapper::Resource)
  klass.storage_names[:default] = @table_name
  klass.property(:id, DataMapper::Types::Serial)
  klass.property(:created_at, DateTime, :nullable => false)
  klass.property(:updated_at, DateTime, :nullable => false)
  columns_with_types { |n, t| klass.property(n, t, :field => n.to_s) }
  klass
end

This lets me take a SAXMachine class (very lightweight) and turn it into a Datamapper class on the fly, and do DataMappery stuff with it. You could even to it to an object's singleton class.

I like to imagine that this lowers my memory footprint when I'm importing 100K objects from XML (I don't use DM for the mass imports), and only mix in the more complex database functions when I need them

like image 78
Michael Sofaer Avatar answered Oct 13 '22 01:10

Michael Sofaer