Permalink
Browse files

Modified registry to look up models by convention

  • Loading branch information...
1 parent 84aecb6 commit 4be1874f61ba318d5e3efc61a33ee2bb8f57cbe1 Evan Light committed Mar 15, 2013
Showing with 47 additions and 8 deletions.
  1. +22 −8 lib/edr/registry.rb
  2. +25 −0 spec/edr/registry_spec.rb
View
@@ -3,21 +3,37 @@
module Edr
class Registry
def self.define(&block)
- @@instance = self.new(&block)
+ @instance = self.new(&block)
end
def self.data_class_for(model_class)
- @@instance.data_class_for(model_class)
+ @instance.data_class_for(model_class)
end
def self.model_class_for(data_class)
- @@instance.model_class_for(data_class)
+ @instance.model_class_for(data_class)
end
+ def self.map_models_to_mappers
+ define unless @instance
+
+ ObjectSpace.each_object do |o|
+ next unless o.is_a?(Class) &&
+ o.ancestors.include?(ActiveRecord::Base) &&
+ o.to_s =~ /Data$/
+ model_name = o.to_s.sub(/Data$/, "")
+
+ next unless Object.const_defined?(model_name)
+
+ model_class = Object.const_get(model_name)
+ @instance.map(model_class, o)
+ end
+ end
+
def initialize(&block)
@data_to_model_map = {}
@model_to_data_map = {}
- self.instance_eval &block
+ #self.instance_eval &block
end
# the mapping is done by the class names, to avoid
@@ -31,14 +47,12 @@ def data_class_for model_class
data_class = @model_to_data_map[model_class.to_s]
return OpenStruct unless data_class
- data_class.constantize
+ Object.const_get(data_class)
end
def model_class_for data_class
model_class = @data_to_model_map[data_class.to_s]
- raise "No model class for #{data_class.to_s}" unless model_class
-
- model_class.constantize
+ model_class ? model_class.constantize : nil
end
private
View
@@ -0,0 +1,25 @@
+require 'spec_helper'
+require_relative '../../lib/edr/registry'
+
+describe Edr::Registry do
+ class HasAModelData < ActiveRecord::Base; end
+ class HasAModel; end
+
+ class DoesntHaveAModelData < ActiveRecord::Base; end
+
+ context "defining domain model to active record mappings" do
+ subject { Edr::Registry }
+
+ before do
+ subject.map_models_to_mappers
+ end
+
+ it "maps every AR::Base with a class name ending in 'Data' to a domain model class with the same name less 'Data'" do
+ expect(subject.model_class_for(HasAModelData)).to eq(HasAModel)
+ end
+
+ it "does not map an AR::Base ending in 'Data' to a domain model if none exist with the same name less 'Data'" do
+ expect(subject.model_class_for(DoesntHaveAModelData)).to be_nil
+ end
+ end
+end

0 comments on commit 4be1874

Please sign in to comment.