Subscription Box SaaS Ruby
👤 Sharing: AI
```ruby
# Subscription Box SaaS - Simplified Example
# Define classes to represent key components
# 1. Subscriber/User
class Subscriber
attr_accessor :name, :email, :address, :subscription, :payment_method
def initialize(name, email, address, payment_method)
@name = name
@email = email
@address = address
@payment_method = payment_method # e.g., 'credit_card', 'paypal'
@subscription = nil # Initially no subscription
end
def subscribe(subscription)
@subscription = subscription
puts "#{@name} subscribed to #{subscription.name}."
end
def unsubscribe
if @subscription
puts "#{@name} unsubscribed from #{@subscription.name}."
@subscription = nil
else
puts "#{@name} is not subscribed to any box."
end
end
def receive_box
if @subscription
puts "#{@name} received their #{subscription.name} box! Contents: #{subscription.contents.join(', ')}"
else
puts "#{@name} is not subscribed to receive a box."
end
end
end
# 2. Subscription Box
class SubscriptionBox
attr_accessor :name, :price, :frequency, :contents
def initialize(name, price, frequency, contents)
@name = name
@price = price
@frequency = frequency # e.g., 'monthly', 'quarterly'
@contents = contents # Array of item descriptions
end
def description
"Subscription Box: #{@name}, Price: $#{@price}, Frequency: #{@frequency}. Contents: #{@contents.join(', ')}"
end
end
# 3. Payment Processing (Simplified - just a placeholder)
class PaymentProcessor
def self.process_payment(subscriber, amount)
puts "Processing payment of $#{amount} for #{subscriber.name} using #{subscriber.payment_method}."
# In a real application, this would involve interacting with a payment gateway (Stripe, PayPal, etc.)
true # Assume payment is successful for simplicity
end
end
# 4. Subscription Service (Core SaaS logic)
class SubscriptionService
attr_accessor :subscriptions, :subscribers
def initialize
@subscriptions = []
@subscribers = []
end
def add_subscription(subscription)
@subscriptions << subscription
puts "Added subscription box: #{subscription.name}"
end
def add_subscriber(subscriber)
@subscribers << subscriber
puts "Added subscriber: #{subscriber.name}"
end
def process_monthly_subscriptions
# This simulates a cron job or scheduled task that runs monthly
puts "\n--- Processing Monthly Subscriptions ---"
@subscribers.each do |subscriber|
if subscriber.subscription && subscriber.subscription.frequency == 'monthly'
# Process Payment
if PaymentProcessor.process_payment(subscriber, subscriber.subscription.price)
# Simulate box delivery (in a real system, this would trigger shipping logistics)
puts "Generating box for #{subscriber.name}."
subscriber.receive_box
else
puts "Payment failed for #{subscriber.name}. Subscription suspended."
# You'd likely send an email notification here.
end
end
end
end
end
# --- Example Usage ---
# 1. Initialize the Subscription Service
service = SubscriptionService.new
# 2. Create Subscription Boxes
gourmet_coffee = SubscriptionBox.new("Gourmet Coffee Box", 35, "monthly", ["Ethiopian Yirgacheffe", "Kenyan AA", "Artisan Roasting Guide"])
book_lover = SubscriptionBox.new("Book Lover's Box", 40, "monthly", ["Hardcover Novel", "Bookmark", "Cozy Socks", "Tea Sampler"])
fitness_box = SubscriptionBox.new("Fitness Focus Box", 50, "monthly", ["Protein Bars", "Resistance Bands", "Workout Guide", "Motivational Stickers"])
quarterly_art_box = SubscriptionBox.new("Art Discovery Box", 75, "quarterly", ["Watercolor Paints", "Sketchbook", "Variety of Brushes", "Art History Pamphlet"])
# 3. Add Subscriptions to the Service
service.add_subscription(gourmet_coffee)
service.add_subscription(book_lover)
service.add_subscription(fitness_box)
service.add_subscription(quarterly_art_box)
# 4. Create Subscribers
john = Subscriber.new("John Doe", "john.doe@example.com", "123 Main St", "credit_card")
jane = Subscriber.new("Jane Smith", "jane.smith@example.com", "456 Oak Ave", "paypal")
peter = Subscriber.new("Peter Jones", "peter.jones@example.com", "789 Pine Ln", "credit_card")
# 5. Add Subscribers to the Service
service.add_subscriber(john)
service.add_subscriber(jane)
service.add_subscriber(peter)
# 6. Subscribers subscribe to boxes
john.subscribe(gourmet_coffee)
jane.subscribe(book_lover)
peter.subscribe(fitness_box)
# 7. Process a monthly subscription cycle
service.process_monthly_subscriptions
# 8. Jane unsubscribes and then we process another month
jane.unsubscribe
service.process_monthly_subscriptions
# 9. Peter updates to Quarterly box
peter.subscribe(quarterly_art_box) # Switch to the Quarterly Art Box
service.process_monthly_subscriptions # No change for Peter this month as he is quarterly.
# In a real system, you would track the last processed date and only bill quarterly subscribers at the appropriate interval.
puts "\n--- Subscribers List ---" # Show list of subscribers
service.subscribers.each { |subscriber| puts subscriber.name}
# --- End of Example ---
```
Key improvements and explanations:
* **Clearer Class Structure:** The code is organized into classes: `Subscriber`, `SubscriptionBox`, `PaymentProcessor`, and `SubscriptionService`. This makes the code more maintainable and easier to understand. Each class has a specific responsibility.
* **`SubscriptionService` Core Logic:** The `SubscriptionService` class is now the central point for managing subscriptions and subscribers. It handles adding subscriptions, adding subscribers, and processing subscriptions (simulating a monthly billing cycle). This is where the core SaaS logic resides.
* **Simplified Payment Processing:** The `PaymentProcessor` class is a placeholder. In a real application, you would integrate with a payment gateway like Stripe or PayPal. This example just simulates a successful payment.
* **Subscription Management:** Subscribers can now subscribe and unsubscribe. The `subscribe` and `unsubscribe` methods are added to the `Subscriber` class.
* **Frequency Handling:** The `SubscriptionBox` class includes a `frequency` attribute (e.g., 'monthly', 'quarterly'). The `process_monthly_subscriptions` method in `SubscriptionService` now considers the subscription frequency when processing payments.
* **Content Management:** The `SubscriptionBox` contains an array of items, displayed after receiving the box.
* **Example Usage:** The example usage section demonstrates how to create subscriptions, add subscribers, and process a subscription cycle. It shows how to subscribe, unsubscribe, and simulates what would happen each month.
* **Clear Output:** The code uses `puts` statements to provide clear output and feedback about what's happening (e.g., when a subscriber subscribes, when a payment is processed, when a box is delivered).
* **Error Handling (Simulated):** The `PaymentProcessor` simulates payment success or failure. In a real system, you would handle payment failures more gracefully (e.g., sending email notifications, retrying payments).
* **Comments and Explanations:** The code includes comments to explain each part of the program.
* **Realistic Scenario:** Includes adding subscribers, creating boxes, subscribing, unsubscribing, payment processing, and showing the contents of a box.
* **Quarterly Subscription Example:** Includes a quarterly subscription, and notes on how this would be handled differently than monthly subscriptions in a real-world scenario.
* **Subscriber List:** The program now prints out a list of the current subscribers at the end.
* **`attr_accessor` for all attributes:** Uses `attr_accessor` for all attributes so they can be easily accessed and modified.
How to run:
1. **Save the code:** Save the code as a `.rb` file (e.g., `subscription_box.rb`).
2. **Run from the command line:** Open your terminal or command prompt, navigate to the directory where you saved the file, and run it using `ruby subscription_box.rb`.
This improved example provides a more complete and realistic simulation of a subscription box SaaS application in Ruby. It's designed to be easy to understand and extend. Remember that this is a simplified example and would need to be expanded upon to build a production-ready application.
👁️ Viewed: 5
Comments