/
sequel_notnaughty.rb
72 lines (62 loc) · 1.86 KB
/
sequel_notnaughty.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
require 'rubygems'
gem 'sequel', '>= 2.5.0'
require 'sequel'
gem 'not-naughty', '= 0.6.2'
require 'not_naughty'
NotNaughty::Validation.load_paths << File.join(%W[#{ File.dirname __FILE__ } validations])
NotNaughty::Validation.load(:acceptance, :confirmation, :format, :length, :numericality, :presence, :uniqueness)
module Sequel #:nodoc:
module Plugins #:nodoc:
# == Adapter for Ruby Sequel
#
# Validate all your Ruby Sequel models with NotNaughty:
#
# class Sequel::Model
# is :notnaughty
# end
#
# Validate just specific models:
#
# class YourModel < Sequel::Model
# is :notnaughty
# end
class NotNaughty < NotNaughty::Validator
# Hook called by plugin api.
def self.apply(receiver, *args)
receiver.extend ::NotNaughty
receiver.validator self, :create, :update
end
# Returns state for given instance.
def get_state(instance)
if instance.new? then @states[:create] else @states[:update] end
end
# Ensures API compatibility.
module InstanceMethods
def validate #:nodoc:
errors.clear
return false if before_validation == false
self.class.validator.invoke self
after_validation
nil
end
end
# Ensures API compatibility.
module ClassMethods
def validations #:nodoc:
validator.states.
inject({}) do |validations, state_with_name|
validations.merge(state_with_name[1].validations) {|k,o,n| o|n}
end
end
def has_validations?() #:nodoc:
validator.has_validations?
end
def validate(instance) #:nodoc:
validator.invoke instance
end
end
end
# this isn't a one-liner...
Notnaughty = NotNaughty
end
end