Hi Jeremy,

I'm working on something that has me a bit puzzled. I'd like to introduce 
an association that depends on a provided value, or fall back to a default.

My plan is to overwrite the getter to accept an optional argument, and then 
to pass it along. But using `super` won't work. I have a method that does, 
but it's the first time I've had to alias a method inside a Sequel model 
and I wonder if there's a better way.

Here's the code and annotated spot.

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)
]

And in case Google eats the formatting, here's a 
gist: https://gist.github.com/adam12/772a7aa99a912ccf71042fd4747d4869

Any comments on the alias or the general implementation would be 
appreciated.

Thanks.

Adam

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sequel-talk+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sequel-talk/9bbd2d00-daad-475c-b22e-961fb6e131f0n%40googlegroups.com.

Reply via email to