Skip to content

Instantly share code, notes, and snippets.

@wdspkr
Last active January 4, 2022 07:24
Show Gist options
  • Save wdspkr/f16503ad02b02d6dc74b4080748c2e79 to your computer and use it in GitHub Desktop.
Save wdspkr/f16503ad02b02d6dc74b4080748c2e79 to your computer and use it in GitHub Desktop.
module InterestRepository
extend self
def my_index
InterestRecord.includes(:account).order(percentage: :desc).all.map do |interest_data|
Interest.new(interest_data.attributes_with_associations)
end
end
def fetch(id)
Interest.new(InterestRecord.includes(:account).find(id)).attributes_with_associations
end
def save(interest)
return false unless interest.valid?
data = interest.id ? InterestRecord.find(interest.id) : InterestRecord.new
data.assign_attributes(interest.attributes)
data.save
end
end
class Interest
include ActiveModel::Model
ATTRIBUTES_FOR_DATA = %i[account_id amount rate].freeze
attr_accessor(*ATTRIBUTES_FOR_DATA, :account, :id, :created_at, :updated_at)
validates :account_id, :amount, :rate, presence: true
def attributes
ATTRIBUTES_FOR_DATA.index_with do |attribute|
send(attribute)
end
end
end
class InterestRecord < ActiveRecord::Base
self.table_name = 'interests'
belongs_to :account
def attributes_with_associations
attributes.merge('account' => account)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment