简体   繁体   中英

Raise ArgumentError if creating class object parameter hash did not met requirments

i have little problem i can't solve. I have Class to which is passed hash with parameters, but i have to raise and error if the parameter count is less or more than 2 and if any of the values are nill.

What could be the best practise here, if i dont want to pass separate parameters, but a hash?

Class:

Class MyClass
  attr_accessor :param1, :param2

  def initialize(attr_hash)

    self.param1 = attr_hash[:param1].to_f
    self.param2 = attr_hash[:param2]

  end
end

and i am passing something like this

instance = MyClass.new({param1: 12, param2: "Ok"})

Is there a raily or more ruby way to achieve what i want, not iterating trough hash and checking if any of the values are empty and if count is less or more than 2?

Don't raise an error if parameter is invalid. Instead, create valid? instance method to check the state.

Also, use Ruby OpenStruct class if you would like to pass hash as input.

require 'ostruct'

class MyClass < OpenStruct

  def valid?
    @table.length > 1    
  end

end

a = MyClass.new(a: :b, c: :d)
a.valid? # true
a.c # :d

a=MyClass.new(a: :b)
a.valid? # false

The following should work:

def initialize(hash)
  raise 'error' if hash.size < 2 or hash.value?(nil)
  self.param1 = hash[:param1].to_f
  self.param2 = hash[:param2]
end

As blelump pointed out this would the better way of creating your class:

require 'ostruct'

class MyClass < OpenStruct

  def valid?
    @table.length > 1 and !@table.value?(nil)   
  end

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM