/
base.rb
100 lines (81 loc) · 2.76 KB
/
base.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
module CouchRest
module Model
class Base < CouchRest::Document
include ActiveModel::Conversion
extend Translation
include Configuration
include Connection
include Persistence
include DocumentQueries
include ExtendedAttachments
include Proxyable
include PropertyProtection
include Associations
include Validations
include Callbacks
include Designs
include CastedBy
include Dirty
def self.subclasses
@subclasses ||= []
end
def self.inherited(subklass)
super
subklass.send(:include, Properties)
subklass.class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.inherited(subklass)
super
subklass.properties = self.properties.dup
# This is nasty:
subklass._validators = self._validators.dup
end
EOS
subclasses << subklass
end
# Instantiate a new CouchRest::Model::Base by preparing all properties
# using the provided document hash.
#
# Options supported:
#
# * :write_all_attributes, true when data comes directly from database so we can set protected and read-only attributes.
# * :database, provide an alternative database
#
# If a block is provided the new model will be passed into the
# block so that it can be populated.
def initialize(attributes = {}, options = {}, &block)
super()
# Always force the type of model
self[self.model_type_key] = self.class.model_type_value
# Some instances may require a different database
self.database = options[:database] unless options[:database].nil?
# Deal with the attributes
write_attributes_for_initialization(attributes, options)
yield self if block_given?
after_initialize if respond_to?(:after_initialize)
run_callbacks(:initialize) { self }
end
def self.build(attrs = {}, options = {}, &block)
end
alias :new_record? :new?
alias :new_document? :new?
# Compare this model with another by confirming to see
# if the IDs and their databases match!
#
# Camparison of the database is required in case the
# model has been proxied or loaded elsewhere.
#
# A Basic CouchRest document will only ever compare using
# a Hash comparison on the attributes.
def == other
return false unless other.is_a?(Base)
if id.nil? && other.id.nil?
# no ids? assume comparing nested and revert to hash comparison
to_hash == other.to_hash
else
database == other.database && id == other.id
end
end
alias :eql? :==
end
end
end