1

I am wondering if there's a more elegant way to say this in Ruby:

FREE_PLAN_MAXIMUM = 1 BASIC_PLAN_MAXIMUM = 10 PREMIUM_PLAN_MAXIMUM = 100 def maximum_entries_per_month case plan when "premium" PREMIUM_PLAN_MAXIMUM when "basic" BASIC_PLAN_MAXIMUM else FREE_PLAN_MAXIMUM end end 

I don't like the repetition of premium and basic inside the function. What might be an alternative?

1
  • What repetition are you seeing? Commented Nov 14, 2013 at 16:36

4 Answers 4

3

It depends on the rest of your code, especially whether you're using those constants in other places. One pattern I've found nice for this kind of thing is a hash, though.

PLAN_MAXIMUMS = { free: 1, basic: 10, premium: 100 } def maximum_entries_per_month PLAN_MAXIMUMS[plan.to_sym] || PLAN_MAXIMUMS[:free] end 
Sign up to request clarification or add additional context in comments.

1 Comment

PLAN_MAXIMUMS.default = 1 and just PLAN_MAXIMUMS[plan.to_sym] would also work.
3

Use Hash#fetch, which allows for a default value, instead of a case statement.

PLAN_MAXIMUMS = { free: 1, basic: 10, premium: 100 } def maximum_entries_per_month PLAN_MAXIMUMS.fetch(plan.to_sym, PLAN_MAXIMUMS[:free]) end 

2 Comments

+1 I'd never seen fetch before, though I also think my naive " || " is pretty concise and readable
Thanks a lot. Since I am still new to Rails I went with spike's syntax because it's easier for me to read and understand.
1

You don't need a method. Just have a hash:

maximum_entries_per_month = Hash.new(1).merge{"premium" => 100, "basic" => 10} 

and call:

maximum_entries_per_month[plan] 

1 Comment

I was about to post the same--just wait 'til I get my new keyboard.
0

what about:

FREE_PLAN_MAXIMUM = 1 BASIC_PLAN_MAXIMUM = 10 PREMIUM_PLAN_MAXIMUM = 100 PLANS = {'premium' => PREMIUM_PLAN_MAXIMUM, 'basic' => BASIC_PLAN_MAXIMUM, 'free' => FREE_PLAN_MAXIMUM} def maximum_entries_per_month PLANS[plan] or FREE_PLAN_MAXIMUM end 

that "or FREE_PLAN_MAXIMUM" will catch any plan that's not "premium", "basic" or "free", if you are sure you only have those three plans just remove that part

EDIT: this way you keep your other constants working

EDIT2: if you don't want to add more constants and you are sure plan is one of those, you can do:

def maximum_entries_per_month self.class.const_get("#{plan.upcase}_PLAN_MAXIMUM") end 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.