Question

I find that I've been doing this a fair enough number of times in my Rails controllers that I'm interested in finding a better way of writing it out (if possible). Essentially, I'm validating the input to a few options, and falling back on a default value if the input doesn't match any of the options.

valid_options = %w(most_active most_recent most_popular)
@my_param = valid_options.include?(params[:my_param]) ? params[:my_param] : 'most_recent'
Was it helpful?

Solution

If you use a hash instead of an array, it would be faster and cleaner. And, since your default is "most_recent", having "most_recent" in valid_options is redundant. You better remove it.

filter_options =
Hash.new("most_recent")
.merge("most_popular" => "most_popular", "most_active" => "most_active")

@my_param = filter_options[params[:my_param]]

OTHER TIPS

I too would go the Hash route.

This could be imaginable:

Hash[valid_options.zip valid_options].fetch(params[:my_param], "most_recent")

A bit farfetched.

valid_options = %w(most_active most_recent most_popular)
(valid_options & [params[:my_param]]).first || 'most_recent'

How is the below:

valid_options = %w(most_active most_recent most_popular)
valid_options.detect(proc{'default_value'}){|i| i == params[:my_param] }

Another one:

valid_options = %w(most_active most_recent most_popular)
valid_options.dup.delete(params[:my_param]) { "default" }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top