Reputation: 11336
Is there an elegant way to accomplish this in Ruby?
if params[:limit] && params[:limit].to_i < 50
@limit = params[:limit].to_i
elsif params[:limit] && params[:limit].to_i > 50
@limit = 50
end
Upvotes: 2
Views: 205
Reputation: 41442
What about this?
if params[:limit]
@limit = [params[:limit].to_i, 50].min
end
Also, your current code may have a bug in it in that it doesn't set @limit if params[:limit] = 50 (you check for > 50 and < 50 but not = 50).
Edit: fl00r's implementation in philosodad's comment is pretty much the same but is more terse. Use his instead.
Upvotes: 2
Reputation: 15605
@limit = params[:limit] && [params[:limit].to_i, 50].min
I think this is the most intention revealing approach.
Upvotes: 1
Reputation: 1808
@limit = [params[:limit].to_i, 50].min unless params[:limit].nil?
Upvotes: 3
Reputation: 5668
@limit = ((1..50).include? params[:limit]) || 50
(nil.to_i is 0, so no need to check it)
Upvotes: 0
Reputation: 83680
limit = params[:limit] && params[:limit].to_i
@limit = limit && limit < 50 ? limit : 50
OR
@limit = params[:limit] && l=params[:limit].to_i && (l < 50 ? l : 50)
And I don't know if you would like to return @limit
as nil in case if params[:limit]
doesn't exist? Because in both cases @limit
won't be initialized as in your example if there is no any params[:limit]
Upvotes: 2
Reputation: 53158
not fully elegant, but shorter
@limit = params[:limit] ? (params[:limit].to_i < 50 ? params[:limit].to_i : 50 ) : nil
I would also consider using attribute of model with callbacks ... not sure how but that might work
Upvotes: 0