Permalink
Browse files

Add Attribute::Class

  • Loading branch information...
1 parent b7c4d5f commit 6e4bd6f51af1490f8b66a294c2ea4f9eebfedf46 @solnic committed Jul 31, 2011
View
@@ -54,6 +54,7 @@ def self.included(descendant)
require 'virtus/attribute/default_value'
require 'virtus/attribute'
require 'virtus/attribute/object'
+require 'virtus/attribute/class'
require 'virtus/attribute/array'
require 'virtus/attribute/boolean'
require 'virtus/attribute/date'
@@ -0,0 +1,21 @@
+module Virtus
+ class Attribute
+
+ # Class
+ #
+ # @example
+ # class Entity
+ # include Virtus
+ #
+ # attribute :type, Class
+ # end
+ #
+ # post = Entity.new(:model => Model)
+ #
+ class Class < Object
+ primitive ::Class
+ coercion_method :to_class
+
+ end # class Class
+ end # class Attribute
+end # module Virtus
@@ -11,6 +11,17 @@ class String < Object
NUMERIC_REGEXP = /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/.freeze
+ # Coerce give value to a constant
+ #
+ # @param [String] value
+ #
+ # @return [Object]
+ #
+ # @api public
+ def self.to_class(value)
+ ::Object.const_get(value)
+ end
+
# Coerce given value to Time
#
# @example
@@ -0,0 +1,24 @@
+require 'spec_helper'
+
+describe Virtus::Attribute::Class do
+ it_should_behave_like 'Attribute' do
+ let(:attribute_name) { :String }
+ let(:attribute_value) { String }
+ let(:attribute_value_other) { 'String' }
+ let(:attribute_default) { 'Object' }
+ let(:attribute_default_proc) { lambda { |instance, attribute| attribute.name.to_s } }
+ end
+
+ describe '#coerce' do
+ let(:attribute) { described_class.new(:type) }
+
+ subject { attribute.coerce(value) }
+
+ context 'with a String' do
+ let(:value) { 'String' }
+
+ it { should be(String) }
+ end
+ end
+
+end
@@ -9,7 +9,7 @@
Virtus::Attribute::Float, Virtus::Attribute::Decimal,
Virtus::Attribute::Numeric, Virtus::Attribute::DateTime,
Virtus::Attribute::Date, Virtus::Attribute::Boolean,
- Virtus::Attribute::Array ]
+ Virtus::Attribute::Array, Virtus::Attribute::Class ]
end
it "should return all known attribute classes" do
@@ -0,0 +1,13 @@
+require 'spec_helper'
+
+describe Virtus::Coercion::String, '.to_class' do
+ subject { object.to_class(string) }
+
+ let(:object) { described_class }
+
+ context "with a String" do
+ let(:string) { 'String' }
+
+ it { should be(String) }
+ end
+end

0 comments on commit 6e4bd6f

Please sign in to comment.