Skip to content

Commit

Permalink
Merge pull request #5 from danifromecuador/feat/validations
Browse files Browse the repository at this point in the history
Feat/validations
  • Loading branch information
danifromecuador authored Oct 30, 2024
2 parents 5661f2a + a530926 commit f40a164
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
29 changes: 29 additions & 0 deletions app/models/transaction.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,32 @@
class Transaction < ApplicationRecord
belongs_to :user
# Validaciones de atributos
validates :user_id, :coin_to_send, :coin_to_receive, :amount_to_send_in_cents_or_sats,
:amount_to_receive_in_cents_or_sats, :btc_usd_exchange_rate, presence: true
# Validaciones personalizadas
validate :minimal_amount_to_send
validate :avoid_transaction_if_insuficient_balance

private

def minimal_amount_to_send
if coin_to_send == 'usd' && amount_to_send_in_cents_or_sats < 1000
errors.add(:minimal_amount,
'La cantidad mínima a enviar debe ser de 1 000 cents o superior')
end
return unless coin_to_send == 'btc' && amount_to_send_in_cents_or_sats < 14_000

errors.add(:minimal_amount,
'La cantidad mínima a enviar debe ser de 14 000 sats o superior')
end

def avoid_transaction_if_insuficient_balance
@user = User.find(user_id)
if coin_to_send == 'usd' && @user.usd_balance_in_cents < amount_to_send_in_cents_or_sats
errors.add(:insuficient_balance, 'No tiene fondos en USD suficientes para realizar esta transacción')
end
return unless coin_to_send == 'btc' && @user.btc_balance_in_sats < amount_to_send_in_cents_or_sats

errors.add(:insuficient_balance, 'No tiene fondos suficientes en BTC para realizar esta transacción')
end
end
13 changes: 13 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
class User < ApplicationRecord
has_many :transactions
# Validaciones de atributos
validates :name, :year_of_birth, :usd_balance_in_cents, :btc_balance_in_sats, presence: true
validates :usd_balance_in_cents, :btc_balance_in_sats, numericality: { greater_than_or_equal_to: 0 }
# Validaciones personalizadas
validate :must_be_of_legal_age

private

def must_be_of_legal_age
return unless year_of_birth.present? && Date.current.year - year_of_birth < 18

errors.add(:year_of_birth, 'El usuario debe ser mayor de edad para registrase')
end
end

0 comments on commit f40a164

Please sign in to comment.