snippetrubyrailsMinor
Convert string array to object with true/false flags
Viewed 0 times
convertwitharraytruefalseflagsobjectstring
Problem
Currently a
The parameter contains comma delimited string - each string id for each category:
I want to get a Ruby object with corresponding attributes that will be
Could this be rewritten in shorter way?
filter parameter of a GET request is used to designate items' categories that will be requested from database and displayed.The parameter contains comma delimited string - each string id for each category:
filter=complete,inwork,cancelled,ycancelled.I want to get a Ruby object with corresponding attributes that will be
true or false dependent on string id presence in filter parameter. Current implementation is as follows:filter = params[:filter].split(',') rescue []
fopt = OpenStruct.new(Hash[%w(complete inwork cancelled ycancelled).map {|fo| [fo.to_sym, filter.include?(fo)]}])Could this be rewritten in shorter way?
Solution
Code looks great to me. Here is a Rubocop-clean version with one change:
Note the Rubocop rule to avoid rescue in its modifier form.
def fopt
filter = (params[:filter] || '').split(',')
OpenStruct.new(Hash[
%w(complete inwork cancelled ycancelled).map do |fo|
[fo.to_sym, filter.include?(fo)]
end
])
endNote the Rubocop rule to avoid rescue in its modifier form.
Code Snippets
def fopt
filter = (params[:filter] || '').split(',')
OpenStruct.new(Hash[
%w(complete inwork cancelled ycancelled).map do |fo|
[fo.to_sym, filter.include?(fo)]
end
])
endContext
StackExchange Code Review Q#75668, answer score: 3
Revisions (0)
No revisions yet.