How to DRY up my ruby exceptions in initialize method?
Asked Answered
B

3

5

I'm writing a program in Ruby with a Product class. I have some exceptions raised whenever the Product is initialized with the wrong type of arguments. Is there a way I can DRY up my raised exceptions (am I even referring to those correctly?) I appreciate the help. Code is below:

class Product
  attr_accessor :quantity, :type, :price, :imported

  def initialize(quantity, type, price, imported)
    raise ArgumentError.new("Type must be a string") if type.class != String
    raise ArgumentError.new("Quantity must be greater than zero") if quantity <= 0
    raise ArgumentError.new("Price must be a float") if price.class != Float

    @quantity = quantity
    @type     = type
    @price    = price.round(2)
    @imported = imported
  end
end
Backset answered 27/10, 2013 at 16:43 Comment(0)
D
10

The idiomatic way is to not do the type checks at all, and instead coerce the passed objects (using to_s, to_f, etc.):

class Product
  attr_accessor :quantity, :type, :price, :imported

  def initialize(quantity, type, price, imported)
    raise ArgumentError.new("Quantity must be greater than zero") unless quantity > 0

    @quantity = quantity
    @type     = type.to_s
    @price    = price.to_f.round(2)
    @imported = imported
  end
end

You will then get the appropriate String/Float/etc. representation of the objects passed, and if they don’t know how to be coerced to those types (because they don’t respond to that method), then you’ll appropriately get a NoMethodError.

As for the check on quantity, that looks a lot like a validation, which you may want to pull out into a separate method (especially if there gets to be a lot of them):

class Product
  attr_accessor :quantity, :type, :price, :imported

  def initialize(quantity, type, price, imported)
    @quantity = quantity
    @type     = type.to_s
    @price    = price.to_f.round(2)
    @imported = imported

    validate!
  end

  private

  def validate!
    raise ArgumentError.new("Quantity must be greater than zero") unless @quantity > 0
  end
end
Disproportionate answered 27/10, 2013 at 17:0 Comment(3)
Thanks Andrew - super fast response and very helpful!Backset
Hey @AndrewMarshall, I was wondering if you could explain the reason why we include the bang on the validate method?Backset
@Backset Simply because it raises an exception in the case of “false”. This convention came from Rails, but is usually only used there (I think) when there’s a non-ban version. Ruby core does the same thing but with destructive (mutating) methods instead. Ultimately preference as there’s no functional effect.Disproportionate
F
1
class Product
  attr_accessor :quantity, :type, :price, :imported

  def initialize(quantity, type, price, imported)
    raise ArgumentError.new "Type must be a string" unless type.is_a?(String)
    raise ArgumentError.new "Quantity must be greater than zero" if quantity.zero?
    raise ArgumentError.new "Price must be a float" unless price.is_a?(Float)

    @quantity, @type, @price, @imported = quantity, type, price.round(2), imported
  end
end
Fomalhaut answered 27/10, 2013 at 16:49 Comment(2)
That's really cool, I didn't know I could set variables like that! Thanks for helping outBackset
Yes, you can :) That is parallel assignment.Proem
C
1

You could do something like the following, though I expect there are gems that do this and more, and do it better:

module ArgCheck
  def type_check(label, arg, klass)
    raise_arg_err label + \
      " (= #{arg}) is a #{arg.class} object, but should be be a #{klass} object" unless arg.is_a? klass
  end

  def range_check(label, val, min, max)
    raise_arg_err label + " (= #{val}) must be between #{min} and #{max}" unless val >= min && val <= max
  end

  def min_check(label, val, min)
  puts "val = #{val}, min = #{min}"
    raise_arg_err label + " (= #{val})  must be >= #{min}" unless val >= min
  end

  def max_check(val, min)
    raise_arg_err label + " (= #{val})  must be <= #{max}" unless val <= max
  end    

  # Possibly other checks here  

  private

  def raise_arg_err(msg)
    raise ArgumentError, msg + "\n  backtrace: #{caller_locations}"
  end   
end

class Product
  include ArgCheck 
  attr_accessor :quantity, :type, :price, :imported

  def initialize(quantity, type, price)
    # Check arguments  
    min_check   'quantity', quantity, 0
    type_check  'type',     type,     String
    type_check  'price',    price,    Float

    @quantity = quantity
    @type     = type
    @price    = price.round(2)
  end
end

product = Product.new(-1, :cat, 3)
#  => arg_check.rb:23:in `raise_arg_err': quantity (= -1)  must be >= 0 (ArgumentError)
#    backtrace: ["arg_check.rb:11:in `min_check'", "arg_check.rb:33:in `initialize'", \
#      "arg_check.rb:43:in `new'", "arg_check.rb:43:in `<main>'"]

product = Product.new(1, :cat, 3)
#  => arg_check.rb:26:in `raise_arg_err': type (= cat) is a Symbol object, \
#       but should be be a String object (ArgumentError)
#       backtrace: ["arg_check.rb:3:in `type_check'", "arg_check.rb:34:in `initialize'", \
#         "arg_check.rb:48:in `new'", "arg_check.rb:48:in `<main>'"]

product = Product.new(1, "cat", 3)
#  => arg_check.rb:23:in `raise_arg_err': price (= 3) must be a Float object (ArgumentError)
#       backtrace: ["arg_check.rb:3:in `type_check'", "arg_check.rb:35:in `initialize'", \
#       "arg_check.rb:53:in `new'", "arg_check.rb:53:in `<main>'"]

product = Product.new(1, "cat", 3.00) # No exception raised

Note that, when run in irb, Kernel#caller_locations brings in a lot of stuff you don't want, that you won't get when run from the command line.

Ctn answered 27/10, 2013 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.