Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #2 from justinfrench/fix_circular_references

Fix circular references
  • Loading branch information...
commit 1163ad3d934588376fc35f4b700eb1f11c1f3a23 2 parents 5960659 + 3b99e79
@stevehodgkiss stevehodgkiss authored
Showing with 60 additions and 7 deletions.
  1. +21 −2 lib/modelling.rb
  2. +39 −5 spec/modelling_spec.rb
View
23 lib/modelling.rb
@@ -80,12 +80,31 @@ def initialize(args = {})
args.each { |name, value| send "#{name}=", value }
end
- def inspect
+ def attributes
hash = {}
self.class.accessors.each do |method_name|
hash[method_name] = send(method_name)
end
hash
end
-
+
+ def inspect
+ attributes_as_nice_string = attributes.collect { |name, value|
+ "#{name}: #{attribute_for_inspect(value)}"
+ }.compact.join(", ")
+ "#<#{self.class} #{attributes_as_nice_string}>"
+ end
+
+ def attribute_for_inspect(value)
+ if value.is_a?(String) && value.length > 50
+ "#{value[0..50]}...".inspect
+ elsif value.is_a?(Date) || value.is_a?(Time)
+ %("#{value.to_s(:db)}")
+ elsif value.class.included_modules.include?(Modelling)
+ "#<#{value.class.to_s}>"
+ else
+ value.inspect
+ end
+ end
+
end
View
44 spec/modelling_spec.rb
@@ -130,12 +130,46 @@ class LambdaTest
User.accessors.should include :name, :age
end
- specify 'provides a Hash of attributes and values through inspect' do
- User.new.inspect.key?(:name).should be_true
- User.new.inspect.key?(:age).should be_true
- User.new(:name => "Joe").inspect[:name].should eq "Joe"
+ specify 'provides a Hash of attributes and values' do
+ User.new.attributes.key?(:name).should be_true
+ User.new.attributes.key?(:age).should be_true
+ User.new(:name => "Joe").attributes[:name].should eq "Joe"
end
-
+
+ specify 'converts the attributes hash to a string for inspect' do
+ u = User.new(:name => "Joe")
+ u.inspect.should == "#<User name: \"Joe\", age: nil, test: 3, fav_colours: [], biggest_gripes: []>"
+ end
+
+ context 'circular references' do
+
+ before do
+ class FirstModel
+ include Modelling
+ attributes :test => lambda { |me| OtherModel.new(me) }
+ end
+
+ class OtherModel
+ include Modelling
+ attributes :owner
+ def initialize(owner)
+ @owner = owner
+ end
+ end
+ end
+
+ it 'should not raise an error when inspecting' do
+ expect { FirstModel.new.inspect }.should_not raise_error(SystemStackError)
+ end
+
+ it 'should show the class name instead of inspecting referenced models' do
+ FirstModel.new.inspect.should include("#<OtherModel>")
+ end
+
+ end
+
+
+
context 'inheritence' do
let(:car) { Car.new }
let(:super_car) { SuperCar.new }
Please sign in to comment.
Something went wrong with that request. Please try again.