lib/ripple/document/validations.rb in ripple-0.6.1 vs lib/ripple/document/validations.rb in ripple-0.7.0

- old
+ new

@@ -12,33 +12,61 @@ # See the License for the specific language governing permissions and # limitations under the License. require 'ripple' module Ripple + + # Raised by <tt>save!</tt> when the document is invalid. Use the + # +document+ method to retrieve the document which did not validate. + # begin + # invalid_document.save! + # rescue Ripple::DocumentInvalid => invalid + # puts invalid.document.errors + # end + class DocumentInvalid < StandardError + include Translation + attr_reader :document + def initialize(document) + @document = document + errors = @document.errors.full_messages.join(", ") + super(t("document_invalid", :errors => errors)) + end + end + module Document module Validations extend ActiveSupport::Concern + extend ActiveSupport::Autoload include ActiveModel::Validations + + autoload :AssociatedValidator module ClassMethods # @private def property(key, type, options={}) prop = super validates key, prop.validation_options unless prop.validation_options.blank? end + + # Instantiates a new record, applies attributes from a block, and saves it + # Raises Ripple::DocumentInvalid if the record did not save + def create!(attrs={}, &block) + obj = create(attrs, &block) + (raise Ripple::DocumentInvalid.new(obj) if obj.new?) || obj + end end module InstanceMethods # @private - def save - valid? && super + def save(options={:validate => true}) + return false if options[:validate] && !valid? + super() end - - # @private - def valid? - @_on_validate = new? ? :create : :update - super + + def save! + (raise Ripple::DocumentInvalid.new(self) unless save) || true end + end end end end