Module: ActiveResource::Validations
- Defined in:
- lib/active_resource/validations.rb
Overview
Module to allow validation of Active Resource objects, which creates an Errors instance for every resource. Methods are implemented by overriding Base#validate or its variants Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression and so on).
Example
class Person < ActiveResource::Base
self.site = "http://www.localhost.com:3000/"
protected
def validate
errors.add_on_empty %w( first_name last_name )
errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
end
def validate_on_create # is only run the first time a new object is saved
unless valid_member?(self)
errors.add("membership_discount", "has expired")
end
end
def validate_on_update
errors.add_to_base("No changes have occurred") if unchanged_attributes?
end
end
person = Person.new("first_name" => "Jim", "phone_number" => "I will not tell you.")
person.save # => false (and doesn't do the save)
person.errors.empty? # => false
person.errors.count # => 2
person.errors.on "last_name" # => "can't be empty"
person.attributes = { "last_name" => "Halpert", "phone_number" => "555-5555" }
person.save # => true (and person is now saved to the remote service)
Class Method Summary collapse
-
.included(base) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#errors ⇒ Object
Returns the Errors object that holds all information about attribute error messages.
-
#save_with_validation ⇒ Object
Validate a resource and save (POST) it to the remote web service.
-
#valid? ⇒ Boolean
Checks for errors on an object (i.e., is resource.errors empty?).
Class Method Details
.included(base) ⇒ Object
:nodoc:
254 255 256 257 258 |
# File 'lib/active_resource/validations.rb', line 254 def self.included(base) # :nodoc: base.class_eval do alias_method_chain :save, :validation end end |
Instance Method Details
#errors ⇒ Object
Returns the Errors object that holds all information about attribute error messages.
284 285 286 |
# File 'lib/active_resource/validations.rb', line 284 def errors @errors ||= Errors.new(self) end |
#save_with_validation ⇒ Object
Validate a resource and save (POST) it to the remote web service.
261 262 263 264 265 266 267 |
# File 'lib/active_resource/validations.rb', line 261 def save_with_validation save_without_validation true rescue ResourceInvalid => error errors.from_xml(error.response.body) false end |
#valid? ⇒ Boolean
Checks for errors on an object (i.e., is resource.errors empty?).
Examples
my_person = Person.create(params[:person])
my_person.valid?
# => true
my_person.errors.add('login', 'can not be empty') if my_person.login == ''
my_person.valid?
# => false
279 280 281 |
# File 'lib/active_resource/validations.rb', line 279 def valid? errors.empty? end |