Skip to content

Instantly share code, notes, and snippets.

@solnic
Created September 26, 2012 17:18
Show Gist options
  • Select an option

  • Save solnic/3789299 to your computer and use it in GitHub Desktop.

Select an option

Save solnic/3789299 to your computer and use it in GitHub Desktop.
Mapper generator using Virtus model
class User
include DataMapper::Model
attribute :id, Integer
attribute :name, String
attribute :age, Integer
end
DataMapper.generate_mapper_for(User) do
key :id
rename :name => :username
end
DataMapper.finalize
module DataMapper
class Mapper::Relation::Base < Mapper::Relation
def self.configure(&block)
instance_exec(&block)
finalize
end
end
module Model
def self.included(model)
model.send(:include, Virtus)
end
end
def self.generate_mapper_for(model, &block)
mapper = Class.new(Mapper::Relation::Base)
mapper.model(model)
mapper.relation_name(Inflector.tableize(model.name))
mapper.repository :postgres
mapper.instance_exec(&block)
model.attribute_set.each do |attribute|
next if mapper.attributes[attribute.name]
mapper.map attribute.name, attribute.options[:primitive]
end
mapper.class_eval do
def self.name
"#{model.name}Mapper"
end
def self.inspect
"<##{name}:#{object_id}>"
end
end
mapper
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment