Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a good question and I appreciate your opinion on not accessing current_user in model.</p> <p>Actually, the Event model should consider even less. A model's main job is to store data and process data related to itself. Pricing is your business logic, not Event model's concern. A event has a price. That's all. No more. </p> <p>See, you have lots of things to consider on pricing. Not only if the user is premium or not. How about some discount if an user is 6 months old in your app? How about some promotion on app's birthday? How about a sale just because you are drunk? All of those would be very complex if you use Event model to process them. Even if you don't need all those features now, better to leave some room to expand. </p> <p>Then where should consider the pricing logic? Apparently Controller is not a good place as well. Let's try service object.</p> <pre><code>class PricingService def initialize(event, user) @user = user @event = event @price = event.price end def get_price # The place for your easily adding rules. Or use some meta programming. # say go through all instance methods starting with "pricing_" pricing_premium_user pricing_app_birthday pricing_old_event @price end def pricing_premium_user @price -= 10 if user.premium? end def pricing_app_birthday @price = @price*0.9 if Time.current.today == APP_BIRTHDAY end def pricing_old_event @price = @price*0.9 if event.created_at &lt; (Time.current - 1.week) end end </code></pre> <p>Then use it in controller</p> <pre><code># Checkout def new @event = method_to_find_event pricing = PricingService.new(@event, current_user) @event.price = pricing.get_price # blah blah end </code></pre> <p>Nice?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload