HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyrailsMinor

Convert string array to object with true/false flags

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertwitharraytruefalseflagsobjectstring

Problem

Currently a 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:

def fopt
  filter = (params[:filter] || '').split(',')
  OpenStruct.new(Hash[
    %w(complete inwork cancelled ycancelled).map do |fo|
      [fo.to_sym, filter.include?(fo)]
    end
  ])
end


Note 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
  ])
end

Context

StackExchange Code Review Q#75668, answer score: 3

Revisions (0)

No revisions yet.