Ruby code to update model values ​​to JSON

I cannot find a way to combine these 2 lines in my ruby ​​code:

def as_json(options={})
  super(options).merge ({ :id => self.id.upcase }) # upcase id
  super(options).reject { |k, v| v.nil? } # reject nil values
end

      

How to manage merge

and reject

in super

?

EDIT: An example of what super (options) returns:

{"id" => "6ea8db7f-18a8-422d-9510-5b615883ed7c", "user_id" => 1, "contact_id" => nil, "manufacturer_id" => nil}

The problem is that contact_id

or producer_id

are nil

.

super(options).reject { |_k, v| v.nil? }.merge(id: id.upcase, contact_id: contact_id.upcase, producer_id: producer_id.upcase) 

      

EDIT 2: this works, but very ugly

super(options).merge(id: id.upcase, contact_id: contact_id ? contact_id.upcase : nil, producer_id: producer_id ? producer_id.upcase : nil).reject { |_k, v| v.nil? } 

      

+3


source to share


1 answer


You can bind as many methods as you need:

def as_json(options={})
  super(options).reject { |k, v| v.nil? }.merge ({ :id => self.id.upcase })
end

      

Here's a slightly more conditional version of your code:



def as_json(options = {})
  super(options).reject { |_k, v| v.nil? }.merge(id: id.upcase)
end

      

  • use spaces when setting argument default value
  • _k

    means k

    not used in the block
  • no need {}

    formerge

  • not necessary self

+3


source







All Articles