From 0780ac1575539c05bbee2735c897c4a31d21e6a3 Mon Sep 17 00:00:00 2001 From: Postmodern Date: Wed, 7 Jul 2010 15:29:51 -0700 Subject: [PATCH] Added DataMapper::Property::Lookup module. The module provides transparent access to Property and Type classes via a const_missing method. --- lib/dm-core.rb | 1 + lib/dm-core/property/lookup.rb | 42 +++++++++++++++++++++++++ spec/semipublic/property/lookup_spec.rb | 26 +++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 lib/dm-core/property/lookup.rb create mode 100644 spec/semipublic/property/lookup_spec.rb diff --git a/lib/dm-core.rb b/lib/dm-core.rb index 06db3e5d..f4946045 100644 --- a/lib/dm-core.rb +++ b/lib/dm-core.rb @@ -102,6 +102,7 @@ module ActiveSupport require 'dm-core/property/time' require 'dm-core/property/class' require 'dm-core/property/discriminator' +require 'dm-core/property/lookup' require 'dm-core/property_set' require 'dm-core/adapters' diff --git a/lib/dm-core/property/lookup.rb b/lib/dm-core/property/lookup.rb new file mode 100644 index 00000000..47a9d196 --- /dev/null +++ b/lib/dm-core/property/lookup.rb @@ -0,0 +1,42 @@ +module DataMapper + class Property + module Lookup + + protected + + # + # Provides transparent access to the Properties defined in + # {Property}. It also provides access to the legacy {Types} namespace. + # + # @param [Symbol] name + # The name of the property to lookup. + # + # @return [Property, Type] + # The property with the given name. + # + # @raise [NameError] + # The property could not be found. + # + # @api private + # + # @since 1.0.1 + # + def const_missing(name) + if const = Property.find_class(name) + return const + end + + # only check within DataMapper::Types, if it was loaded. + if DataMapper.const_defined?(:Types) + if DataMapper::Types.const_defined?(name) + type = DataMapper::Types.const_get(name) + + return type if type < DataMapper::Type + end + end + + super + end + end + end +end diff --git a/spec/semipublic/property/lookup_spec.rb b/spec/semipublic/property/lookup_spec.rb new file mode 100644 index 00000000..b069455b --- /dev/null +++ b/spec/semipublic/property/lookup_spec.rb @@ -0,0 +1,26 @@ +require File.expand_path(File.join(File.dirname(__FILE__), '../..', 'spec_helper')) +require 'dm-core/property/lookup' + +describe DataMapper::Property::Lookup do + supported_by :all do + before(:all) do + @klass = Class.new { extend DataMapper::Model } + + DataMapper::Types::LegacyType = Class.new(DataMapper::Types::Text) + end + + it "should provide access to Property classes" do + @klass::Serial.should == DataMapper::Property::Serial + end + + it "should provide access to legacy Types" do + @klass::LegacyType.should be(DataMapper::Types::LegacyType) + end + + it "should not provide access to unknown Property classes" do + lambda { + @klass::Bla + }.should raise_error(NameError) + end + end +end