-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.rb
75 lines (62 loc) · 1.99 KB
/
user.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
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string
# balance :integer default(0), not null
# penning :boolean default(FALSE), not null
# created_at :datetime not null
# updated_at :datetime not null
# key :string
#
class User < ApplicationRecord
include FriendlyId
friendly_id :name, use: :finders
devise :timeoutable, :omniauthable, :omniauth_providers => [:zeuswpi]
has_many :incoming_transactions,
class_name: 'Transaction', foreign_key: 'creditor_id'
has_many :outgoing_transactions,
class_name: 'Transaction', foreign_key: 'debtor_id'
has_many :incoming_requests,
class_name: 'Request', foreign_key: 'debtor_id'
has_many :outgoing_requests,
class_name: 'Request', foreign_key: 'creditor_id'
has_many :notifications
has_many :android_device_registration_tokens, class_name: 'AndroidDeviceRegistrationToken', foreign_key: 'user_id'
has_many :issued_transactions, as: :issuer, class_name: 'Transaction'
has_many :bank_transfer_requests
validates :name, presence: true, uniqueness: true
scope :humans, -> { where.not(id: self.zeus) }
def transactions
Transaction.where('creditor_id = ?', id).or(Transaction.where('debtor_id = ?', id))
end
def requests
Request.where('debtor_id = ?', id).or(Request.where('creditor_id = ?', id).or(Request.where('issuer_id = ?', id)))
end
def calculate_balance!
balance = incoming_transactions.sum(:amount) -
outgoing_transactions.sum(:amount)
self.update_attribute :balance, balance
end
def self.from_omniauth(auth)
where(name: auth.uid).first_or_create do |user|
user.name = auth.uid
user.generate_key!
end
end
def self.zeus
@@zeus ||= find_or_create_by name: 'Zeus'
end
def generate_key
set_key unless self.key
end
def generate_key!
set_key
self.save
end
private
def set_key
self.key = SecureRandom.base64(16)
end
end