-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.rb
73 lines (57 loc) · 1.44 KB
/
models.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
module IdRecord
def id
IdRecord.hex(super)
end
def self.hex(binary)
binary.unpack('H*').first.upcase
end
def self.unhex(str)
[str].pack('H*')
end
def self.included(o)
o.extend(ClassMethods)
end
module ClassMethods
def find(*args)
args = [IdRecord.unhex(args.first)] unless args.length > 1 || args.first.is_a?(Array) # workaround if just ID is passed
super *args
end
def exists?(conditions = :none)
conditions = IdRecord.unhex(conditions) if conditions.is_a?(String) # workaround if just ID is passed
super conditions
end
end
end
module Liquidable
def to_liquid
data = serializable_hash
self.class.reflect_on_all_associations.each do |association|
data[association.name.to_s] = self.send(association.name)
end
data
end
end
class Item < ActiveRecord::Base
include IdRecord
include Liquidable
def user_id
IdRecord.hex(super)
end
belongs_to :user
has_many :ratings, foreign_key: 'item'
has_many :rating_users, through: :ratings, source: :user
end
class User < ActiveRecord::Base
include IdRecord
include Liquidable
has_many :items, dependent: :restrict
has_many :ratings, foreign_key: 'user'
has_many :rated_items, through: :ratings, source: :item
end
class Rating < ActiveRecord::Base
include Liquidable
belongs_to :item, foreign_key: 'item'
belongs_to :user, foreign_key: 'user'
end
class DigestAuthToken < ActiveRecord::Base
end