Skip to content

Commit

Permalink
add errors to conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
al6x committed Oct 11, 2011
1 parent ef1ad33 commit 3237c8b
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 33 deletions.
10 changes: 8 additions & 2 deletions lib/mongo/model/conversion.rb
Expand Up @@ -28,7 +28,7 @@ def to_rson options = {}
profile_options = self.class.profiles[profile] || raise("profile :#{profile} not defined for #{self.class}!")
to_rson profile_options.merge(_profile: profile)
else
options.validate_options! :only, :except, :methods, :_profile
options.validate_options! :only, :except, :methods, :errors, :_profile
child_options = options[:_profile] ? {profile: options[:_profile]} : {}

instance_variables = Mongo::Object.instance_variables(self)
Expand All @@ -47,13 +47,19 @@ def to_rson options = {}
end

methods = options[:methods] ? Array(options[:methods]) : []

methods.each do |method|
value = send method
value = Mongo::Object.convert value, :to_rson, child_options
result[method.to_s] = value
end

with_errors = options.include?(:errors) ? options[:errors] : true
if with_errors and !(errors = self.errors).empty?
stringified_errors = {}
errors.each{|k, v| stringified_errors[k.to_s] = v}
result['errors'] = stringified_errors
end

result
end
end
Expand Down
3 changes: 2 additions & 1 deletion lib/mongo/model/model.rb
Expand Up @@ -4,7 +4,8 @@ module Mongo::Model
attr_accessor :_id, :_class

def _id?; !!_id end
def new_record?; !_id end
def new?; !_id end
alias_method :new_record?, :new?

inherited do
unless is?(Array) or is?(Hash)
Expand Down
18 changes: 18 additions & 0 deletions spec/conversion_spec.rb
Expand Up @@ -82,6 +82,24 @@ def build_post_with_comment
]
}
end

it "should include errors" do
Post.class_eval do
validates_presence_of :token
end

post = Post.new text: 'StarCraft releasing soon!'
post.valid?.should be_false

post.to_rson.should == {
'text' => 'StarCraft releasing soon!',
'errors' => {"token" => ["can't be empty"]}
}

post.to_rson(errors: false).should == {
'text' => 'StarCraft releasing soon!'
}
end

it "to_json" do
post = build_post_with_comment
Expand Down
30 changes: 0 additions & 30 deletions todo/rson.rb

This file was deleted.

0 comments on commit 3237c8b

Please sign in to comment.