You can hook into various credit-related events using callbacks in your usage_credits.rb initializer. These callbacks are useful for analytics, notifications, or triggering business logic like upselling.
Important: Callbacks are executed synchronously during the credit operation. To prevent slowing down your application, avoid heavy operations inside callbacks. Instead, use them to enqueue background jobs (e.g., using deliver_later or perform_later).
Available Callbacks:
on_credits_added: After credits are added to a walleton_credits_deducted: After credits are deducted from a walleton_low_balance_reached: When balance drops below threshold (fires once per crossing)on_balance_depleted: When balance reaches exactly zeroon_insufficient_credits: When an operation fails due to insufficient creditson_credit_pack_purchased: After a credit pack purchase is fulfilledon_subscription_credits_awarded: After subscription credits are awarded
UsageCredits.configure do |config|
# Example: Notify user when balance is low
config.on_low_balance_reached do |ctx|
LowCreditsMailer.buy_more(ctx.owner, remaining: ctx.new_balance).deliver_later
end
# Example: Log failed operations
config.on_insufficient_credits do |ctx|
Rails.logger.info "[Credits] User #{ctx.owner.id} needs #{ctx.amount}, has #{ctx.metadata[:available]}"
end
end