Demian Sims
Demian Sims

Reputation: 921

How to replace nil and 'empty string' with "None" in Ruby/Rails in enumerable object?

I'm taking to objects in Rails: a Record::ActiveRecord_Relation and a ActionController::Parameters and turn them into usable Hashes to be rendered in Views. I need to replace nil and "" with "none". I could do it the non-dry way and protect every key/value pair of the Hash with something like:

  <div><%= @records_incoming[:time_inserted] || @records_incoming[:time_inserted].empty? ? "none" : @records_incoming[:time_inserted]  %></div>

but that doesn't seem very Ruby like (granted, I'm a newer developer).

I've tried to handle this in the controller like so:


def show
    sent_results = Record.get_sent(params[:request][:trans_uuid]) 

    if !sent_results.empty? 

      incoming_request = params[:request].permit!
      @records_sent = sent_results[0].attributes.each { |k,v| v.class == String && v.empty? || !v ? sent_results[0].attributes[k] = "none" : sent_results[0].attributes[k] } 
      @records_incoming = incoming_request.to_h.map { |k, v| v.empty? || !v ? "none" : v }
      byebug 
    else    
      flash[:error] = 'No record found'
    end 
  end

but this does not change the nil and empty string values to 'none'. If I use map, I of course get an array as the return value but I need to retain a Hash.

Please advise on any better Rails ways to do this overall. Trying to get 2 hashes into views to be split out and rendered.

Upvotes: 1

Views: 3701

Answers (2)

Sujan Adiga
Sujan Adiga

Reputation: 1371

You can use transform_values! on params hash

try,

incoming_request.transform_values! { |v| v.empty? || !v ? "none" : v }
@records_incoming = incoming_request

Ref: transform_values! doc

Note: transform_values! updates the hash in place

Upvotes: 2

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

You can try using presence.

<%= @records_incoming[:time_inserted].presence || "none" %>

It handles the two cases you need, @records_incoming[:time_inserted] being nil or an empty string as it returns the receiver if it's present?.

Upvotes: 4

Related Questions