-
-
Save jnunemaker/213030 to your computer and use it in GitHub Desktop.
troubleshooting mongo mapper issue for someone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ruby test_custom_data.rb | |
Loaded suite test_custom_data | |
Started | |
.F.. | |
Finished in 0.018501 seconds. | |
1) Failure: | |
test_creating_a_thing_with_a_foo(MyTest) [test_custom_data.rb:58]: | |
<"--- !ruby/object:Foo \nfirst: 1st\nsecond: 2nd\n"> expected but was | |
<#<Foo:0x1023a5ce8 @first="1st", @second="2nd">>. | |
4 tests, 5 assertions, 1 failures, 0 errors |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'test/unit' | |
require 'mongo_mapper' | |
require 'yaml' | |
MongoMapper.database = 'test_custom_data' | |
class Foo | |
attr_reader :first, :second | |
def initialize first, second | |
@first, @second = first, second | |
end | |
def self.to_mongo(value) | |
return value if value.nil? | |
if value | |
# check if value is already yamlized and if so just return it | |
if value =~ /^---/ | |
value | |
else | |
YAML.dump(value) | |
end | |
else | |
nil | |
end | |
end | |
def self.from_mongo(value) | |
value ? YAML.load(value) : nil | |
end | |
# so foos know if they are equal | |
def ==(other) | |
other.is_a?(self.class) && first == other.first && second == other.second | |
end | |
end | |
class Thing | |
include MongoMapper::Document | |
key :title, String | |
key :name, Foo | |
end | |
class MyTest < Test::Unit::TestCase | |
def test_foo_is_serializable | |
foo = Foo.new("1st", "2nd") | |
assert_equal Foo.to_mongo(foo), YAML.dump(foo) | |
end | |
def test_foo_is_deserializable | |
foo = Foo.new("1st", "2nd") | |
as_yaml = YAML.dump(foo) | |
assert_equal Foo.from_mongo(as_yaml), YAML.load(as_yaml) | |
end | |
def test_serialization | |
foo = Foo.new('1st', '2nd') | |
assert_equal(foo, Foo.from_mongo(Foo.to_mongo(foo))) | |
end | |
def test_creating_a_thing | |
t = Time.now.to_s | |
thing = Thing.find(Thing.create(:title => t).id) | |
assert_equal thing.title, t | |
end | |
def test_creating_a_thing_with_a_foo | |
foo = Foo.new("1st", "2nd") | |
t = Time.now.to_s | |
thing = Thing.find(Thing.create(:title => t, :name => foo).id) | |
assert_equal t, thing.title | |
assert_equal foo, thing.name | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment