2017-06-12 53 views
1

我有以下的Ruby类:异常纯Ruby应用程序

class Money 
    attr_accessor :amount, currency 

    def initialize(amount, currency) 
    @amount = amount 
    @currency = currency 
    end 
end 

比方说,我创建一个类像的一个实例:

money = Money.new(0, 'BR') 

很明显,我不应该能够创建一个金额小于或等于0的金额。在这种情况下,我想为我的课程创建一个自定义例外。在纯ruby应用程序中完成它的最佳方式是什么?

回答

2

你也可以内部Money类中创建,就像这样:

class Money 
    InvalidAmountError = Class.new(StandardError) 

    attr_accessor :amount, :currency 

    def initialize(amount, currency) 
    raise InvalidAmountError, "Amount must be greater than 0" if amount <= 0 

    @amount = amount 
    @currency = currency 
    end 
end 

测试它:

> Money.new(0, 'BR') 
> Money::InvalidAmountError: Amount must be greater than 0 
+1

什么是使用的原因动态类创建,而不是只是'class InvalidAmountError

+0

@JörgWMittag只是一个风格问题,我尝试遵循这个[Ruby风格指南](https://github.com/bbatsov/ruby-style-guide/blob/master/README.md#single-line-classes)只要有可能。 – Gerry

0
class InvalidCurrency < StandardError 
    ... some logic 
end 

class Money 
    attr_accessor :amount, currency 

    def initialize(amount, currency) 
    raise InvalidCurrency unless amount > 0 
    @amount = amount 
    @currency = currency 
    end 
end 

结账this blog更多细节