Skip to content

Instantly share code, notes, and snippets.

@cavebatsofware
Created October 9, 2013 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cavebatsofware/6901632 to your computer and use it in GitHub Desktop.
Save cavebatsofware/6901632 to your computer and use it in GitHub Desktop.
The "ActiveMapper" concept. Some terms could use refactoring.
require 'active_record'
require 'yaml'
require 'pry'
dbconfig = YAML::load_file('config/database.yml')
ActiveRecord::Base.establish_connection(dbconfig)
class String
def camelize
self.split('_').map {|w| w.capitalize}.join
end
end
class ActiveMapper
def self.set_relations(relation_hash_string)
eval <<-qot
def relations
@relations ||= #{relation_hash_string}
end
qot
end
def self.set_relation(klass_name, attrs)
attrs.each do |attr|
eval <<-qot
def #{attr}
relations[:#{klass_name}].#{attr}
end
def #{attr}=(value)
relations[:#{klass_name}].#{attr} = value
end
qot
end
end
def initialize(attrs = {})
keys = relations.keys
if attrs[:id]
keys.each do |key|
relations[key] = eval(key.to_s.camelize).find(attrs[:id])
end
else
keys.each do |key|
relations[key] = eval(key.to_s.camelize).new
end
keys = attrs.keys
keys.each do |key|
self.send(key.to_s, [attrs[key]])
end
end
end
end
class Order < ActiveMapper
set_relations "{orders_relation: nil, order_details_relation: nil}"
set_relation :orders_relation, [:client_id, :status, :ship_date]
set_relation :order_details_relation, [:customer_number]
end
class OrdersRelation < ActiveRecord::Base
self.table_name = :orders
self.primary_key = :order_id
end
class OrderDetailsRelation < ActiveRecord::Base
self.table_name = :order_details
self.primary_key = :order_id
end
binding.pry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment