diff --git a/lib/mongo/model/conversion.rb b/lib/mongo/model/conversion.rb index 9480740..d2cb852 100644 --- a/lib/mongo/model/conversion.rb +++ b/lib/mongo/model/conversion.rb @@ -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) @@ -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 diff --git a/lib/mongo/model/model.rb b/lib/mongo/model/model.rb index a56cfb8..d8267e5 100644 --- a/lib/mongo/model/model.rb +++ b/lib/mongo/model/model.rb @@ -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) diff --git a/spec/conversion_spec.rb b/spec/conversion_spec.rb index 8ef8939..6d7e134 100644 --- a/spec/conversion_spec.rb +++ b/spec/conversion_spec.rb @@ -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 diff --git a/todo/rson.rb b/todo/rson.rb deleted file mode 100644 index 000a6ec..0000000 --- a/todo/rson.rb +++ /dev/null @@ -1,30 +0,0 @@ -module Mongoid::RadMiscellaneous - extend ActiveSupport::Concern - - def to_rson options = {} - with_errors = if options.include?('errors') - options.delete 'errors' - elsif options.include?(:errors) - options.delete :errors - else - true - end - - # standard MongoMaper as_json conversion - hash = as_json(options) - - # MongoMaper fix - hash['id'] = hash.delete('_id').to_s if hash.include? '_id' - - # adding errors - if with_errors - errors = {} - errors.each do |name, list| - errors[name.to_s] = list - end - hash['errors'] = errors unless errors.empty? - end - - hash - end -end \ No newline at end of file