Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to check child params?

Is there a better way to check for items_attributes than the following code? I have to check params[:order] first since sometimes that may not exist, but I hate the look of the long conditional.

if params[:order] and params[:order][:items_attributes]

UPDATE for ruby 2.3, now you can use the dig method

params.dig(:order, :item_attributes)
like image 677
John Pollard Avatar asked Nov 10 '22 12:11

John Pollard


1 Answers

You can create helper method for easier work with nested hashes. Create ruby_ext.rb file in your lib folder, and write this function:

module RubyExt
  module SafeHashChain
    def safe(*args)
      if args.size == 0 then self # Called without args ...
      elsif args.size == 1 then self[args[0]] # Reached end
      elsif self[args[0]].is_a?(Hash) then self[args[0]].safe(*args[1..-1])
      else nil end # Reached end-value too soon
    end
  end
end

class Hash; include RubyExt::SafeHashChain; end

After this you can call safe method on nested hashes like this:

params.safe(:order,:items_attributes)

It will return value from items_attributes. If order or items_attributes don`t exist it will return nil.

like image 167
Vladan Markovic Avatar answered Nov 15 '22 12:11

Vladan Markovic