Skip to content

Instantly share code, notes, and snippets.

@hryk
Created April 14, 2012 11:28
Show Gist options
  • Select an option

  • Save hryk/2383734 to your computer and use it in GitHub Desktop.

Select an option

Save hryk/2383734 to your computer and use it in GitHub Desktop.
example code for dm-validations
#!/usr/bin/env ruby
require 'rubygems'
require 'dm-core'
require 'dm-validations'
require 'dm-transactions'
require 'dm-migrations'
require 'dm-types'
class Card
include DataMapper::Resource
property :id, Serial
property :location, String
property :mac_addr, String, :required => true,
:unique_index => :mac_addr_upload_key_uniq
property :upload_key, String, :required => true,
:unique_index => :mac_addr_upload_key_uniq
has n, :photos
end
class Photo
include DataMapper::Resource
property :id, Serial
property :width, Integer
property :height, Integer
property :path, String
property :created_at, DateTime
property :deleted_at, ParanoidDateTime, :required => false
belongs_to :card
# http://datamapper.org/docs/validations.html
#
# before :create, :set_filepath # <= not working.
before :valid?, :set_filepath # <= working
def set_filepath
if attribute_get(:path).nil?
attribute_set :path, 'hey!'
end
end
end
DataMapper.finalize
DataMapper::Logger.new($stderr, :debug)
DataMapper.setup(:default, "sqlite::memory:")
DataMapper.auto_migrate!
# Insert card information for development
card = Card.new(:mac_addr => 'dummy',
:upload_key => 'dummy',
:location => 'Room')
unless card.save
puts "validation error #1"
card.errors.each do |e|
puts e
end
else
puts "valid entry (card)."
end
photo = card.photos.new(:width => 1,
:height => 1)
unless photo.save
puts "validation error #2"
photo.errors.each do |e|
puts e
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment