Skip to content

Instantly share code, notes, and snippets.

@snusnu
Created August 11, 2008 15:55
Show Gist options
  • Save snusnu/4877 to your computer and use it in GitHub Desktop.
Save snusnu/4877 to your computer and use it in GitHub Desktop.
class MyModel
include DataMapper::Resource
# adds self.validate_constraint
# validation will be performed in specified before callbacks
include DataMapper::Validations::Constraints
# validate an existing constraint (expects class MyConstraint to be loaded)
validate_constraint :my_constraint,
:before => :create # defaults to :save
:expect => [
[ :foo, :to_be => "overwritten MyConstraint expectation value" ]
]
validate_constraint :before => :create, :include => "MyExpectations" do |c|
# add new expectations to this anonymous constraint
c.expect :new_value_1, :to_be => 666
c.expect :new_value_2, :to_be => "foo"
# override an expectation from included MyExpectations module
c.expect :my_foo, :to_be => "not_your_foo"
# define a helper method on this anonymous constraint's singleton class
def c.my_helper
"number of the beast"
end
# add expectation using helper
c.expect :my_helper_value, :to_be_the_result_of => :my_helper
end
end
class MyConstraint
# adds self#valid?
# adds self#expectations
# adds self#expect
# adds self.expect
include Validations::Constraint
attr_accessor :foo_model, :bar_model
def initialize(foo_model, bar_model)
@foo_model, @bar_model = foo_model, bar_model
end
# all calls to expect register an expectation in self#expectations
# self#valid? checks that expectations.all? { |e| e.valid? }
# generates attr_accessor :foo
# expects self#foo to return 3
expect :foo, :to_be => 3
expect :status, :on => :foo_model, :to_be => "closed"
expect :status, :on => :bar_model, :to_be => "approved"
# generates attr_accessor :bar
# expects self#bar to return the same as self#send(:my_validation)
expect :bar, :to_be_the_result_of => :my_validation
def my_validation
foo * 3 == 9
end
end
module MyExpectations
def my_foo
"my_foo"
end
def my_bar
"my_bar"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment