Search code examples
ruby-on-railsrubyruby-on-rails-5ruby-2.0

Best way to clean up/shorten method with too many params & still enforce strict/non-missing params


I currently have a method with a lot of strict params that I want to shorten:

build_receipt(order_id:, order_rate:, ..... invoice_id:, invoice_date:...)
.
.

I'm thinking of grouping these up into hashes like so:

build_receipt(order_details: {}, invoice_details: {})

Would anyone know a sane way I can do the above while still throwing an error whenever a param is missing without explicitly having to write a validation for every key in the above hashes line by line (or if there is a better way the above method can be shortened)?


Solution

  • You can continue on from that and count the number of keys passed in, and that there are no missing values:

    def build_receipt(order_details={}, invoice_details={})
      return if order_details.merge(invoice_details).keys.count != 5 or order_details.merge(invoice_details).values.any?{|v| v.nil? }
      #do something
    end