alex.bour
alex.bour

Reputation: 2964

Ruby code to update model values in JSON

I can't find a way to merge 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: example of what super(options) returns:

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

The problem is when 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 is working but it's 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? } 

Upvotes: 3

Views: 44

Answers (1)

Andrey Deineko
Andrey Deineko

Reputation: 52357

You can chain as many methods as you need to:

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

Here's somewhat more conventional version of your code:

def as_json(options = {})
  super(options).reject { |_k, v| v.nil? }.merge(id: id.upcase)
end
  • use spaces while setting default value of an argument
  • _k means that k is not used in the block
  • no need for {} in the merge
  • no need for self

Upvotes: 3

Related Questions