简体   繁体   中英

Rails render buttons by really complex condition

My rails application members may have one of the two different roles: vip_lite and vip. They can subscribe plan to renew their authorizing.

We also have four types plan: vip_lite/monthly, vip_lite/yearly, vip/monthly, vip/yearly.

A vip user might be subscribing one of the four plans, so does vip_lite. Member with different roles and different plans can see different buttons in plan page(eg vip_lite and subscribing vip_lite/monthly member can see 'upgrade' button in vip plan page).

see the following sample code: (currently write in helper)

def plan_action_button(user)
  if user.vip? && user.subscribing_plan?(:vip_lite, :monthly)
    'button_a'
  elsif user.vip? && user.subscribing_plan?(:vip_lite, :yearly)
    'button_b'
  elsif user.vip? && user.subscribing_plan?(:vip, :monthly)
    'button_c'
  elsif user.vip? && user.subscribing_plan?(:vip, :monthly)
    'button_d'
  elsif user.vip_lite? && user.subscribing_plan?(:vip, :monthly)
    'button_e'
  elsif user.vip_lite? && user.subscribing_plan?(:vip, :yearly)
    'button_e'      

    ... and so on...
  end
end

So I have to deal with 2 * 4 = 8 conditions for each button in these pages. Is there a good pattern in rails for dealing with such case? Thanks

There are some interesting patterns that you can use here. Let's see what's repeated the most: user.vip?

Let's start the method with a guard clause

def plan_action_button(user)
  return 'whatever you need to return' unless user.vip?

  if user.subscribing_plan?(:vip_lite, :monthly)
   'button_a'
[...]

Then because there's a lot of combinaisons, it's hard to tell what changes and what remains the same for those buttons. Is it a I18n key? Is is the button tag with different links? Do you have access to those parts separately like user.plan_name and user.plan_frequency ?

Answering those questions would help you a lot in seeing emerge a pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM