Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to DRY up my ruby exceptions in initialize method?

Tags:

ruby

raise

dry

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
like image 614
Brian Avatar asked Oct 27 '13 16:10

Brian


Video Answer


3 Answers

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
like image 52
Andrew Marshall Avatar answered Oct 19 '22 02:10

Andrew Marshall


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
like image 26
Philidor Avatar answered Oct 19 '22 03:10

Philidor


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.

like image 1
Cary Swoveland Avatar answered Oct 19 '22 04:10

Cary Swoveland