From: Robert Klemme Date: 2013-06-12T20:51:14+09:00 Subject: Re: How would I refactor these four `unless` statements? --0015176f0b9866473a04def3a1d8 Content-Type: text/plain; charset=ISO-8859-1 On Tue, Jun 11, 2013 at 9:38 PM, Rafal C. wrote: > Let's say I have the following four `unless` statements in a row. At > first I thought about using `if` and `elsif` statements and negate the > condition but I'm not sure which way is suitable/readable/good-practice. > > unless @params.include?(:js_code) || @params.include?(:code_url) > raise BadParameters, 'You must include at least one...' > end > unless @params.include?(:compilation_level) > raise BadParameters, 'The :compilation_level...' > end > unless @params.include?(:output_format) > raise BadParameters, 'The :output_format...' > end > unless @params.include?(:output_info) > raise BadParameters, 'The :output_info...' > end > As one can see there are many options. Here's another one MANDATORY = [:js_code, :code_url, ...] ... missing = MANDATORY.reject do |key| @params.include? key end raise BadParameters, "These parameters are missing: #{missing.join ", "}" unless missing.empty? Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ --0015176f0b9866473a04def3a1d8 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable



On Tue, Jun 11, 2013 at 9:38 PM, Rafal C. <lists@ruby-forum.com= > wrote:
Let's say I have the following four `unl= ess` statements in a row. At
first I thought about using `if` and `elsif` statements and negate the
condition but I'm not sure which way is suitable/readable/good-practice= .

=A0 unless @params.include?(:js_code) || @params.include?(:code_url)
=A0 =A0 raise BadParameters, 'You must include at least one...'
=A0 end
=A0 unless @params.include?(:compilation_level)
=A0 =A0 raise BadParameters, 'The :compilation_level...'
=A0 end
=A0 unless @params.include?(:output_format)
=A0 =A0 raise BadParameters, 'The :output_format...'
=A0 end
=A0 unless @params.include?(:output_info)
=A0 =A0 raise BadParameters, 'The :output_info...'
=A0 end

As one c= an see there are many options. =A0Here's another one

MANDATORY =3D [:js_code,= :code_url, ...]
...

missing =3D MANDATORY.reject do |key|
=A0 @params.include? key
end

raise BadParameters, "These parameters are missing: #{mi= ssing.join ", "}" unless missing.empty?

Cheers

robert

--
remember.guy do |as, often| as.yo= u_can - without end
http://blog.rubybestpractice= s.com/
--0015176f0b9866473a04def3a1d8--