-
-
Save adam12/772a7aa99a912ccf71042fd4747d4869 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DB.create_table(:subscriptions) do | |
primary_key :id | |
end | |
DB.create_table(:discounts) do | |
primary_key :id | |
column :valid_until, Date | |
foreign_key :subscription_id, :subscriptions | |
end | |
class Subscription < Sequel::Model | |
one_to_many :discounts | |
one_to_one :active_discount, class: :Discount do |ds| | |
ds.where { valid_until >= Sequel.delay { |ds| ds.opts[:invoice_date] || Sequel::CURRENT_TIMESTAMP }} | |
end | |
# Is there a better way than using an alias here? super won't work inside the method | |
alias_method :original_active_discount, :active_discount | |
def active_discount(invoice_date = nil) | |
if invoice_date | |
original_active_discount { |ds| ds.clone(invoice_date: invoice_date) } | |
else | |
original_active_discount | |
end | |
end | |
end | |
class Discount < Sequel::Model | |
end | |
subscription = Subscription.create | |
subscription.add_discount(valid_until: Date.today + 3) | |
pp Hash[ | |
DEFAULT_ACTIVE_DISCOUNT: Subscription.first.active_discount, | |
RESTRICTED_ACTIVE_DISCOUNT: Subscription.first.active_discount(Date.today) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment