0

抱歉,如果我的问题很愚蠢,但是我花了很多时间搜索解决方案,但没有找到。

我想创建一个ApiOutputsHandler没有数据库的模型。所以我创建了一个 ActiveModel。此模型将用于我的 API 的自定义响应,例如错误(但不仅限于)。我已经使用 send() 方法将属性添加到这个模型中,但认为它非常糟糕......

class ApiOutputsHandler

  attr_accessor :status, :type, :message, :api_code, :http_code, :template

  ERR_TYPES = {
    :permanent_quota_limit => { :type => 'PermanentLimitException', :message => 'Quota limit reached for this action', :api_code => 700, :http_code => 401 } 
  }

  def initialize(data)
    data.each do |name, value|        
      send("#{name}=", value)  
    end
  end

  def error()
    send('status=','error')
    send('template=','api/v1/api_outputs_handler/output')
    return self
  end

  def new
    return self
  end

end

然后,我像这样实例化我的对象

@output = ApiOutputsHandler.new(ApiOutputsHandler::ERR_TYPES[:permanent_quota_limit]) 
return @output.error()

我会花很多钱ERR_TYPES(这就是兴趣)。你认为有更好的方法吗?

当我检查创建的对象时,它看起来像这样:

#<ApiOutputsHandler:0x000000036a6cd0 @type="PermanentLimitException", @message="Quota limit reached for this action">

你看到属性前面的香气了吗?为什么我得到那个而不是常见的:

#<ApiOutputsHandler:0x000000036a6cd0 type: "PermanentLimitException", message: "Quota limit reached for this action">

感谢您的帮助!

4

1 回答 1

2

是的,有更好的方法来做到这一点。以下是我将如何去做:

class ApiOutputsHandler
  attr_accessor :status, :type, :message, :api_code, :http_code, :template

  ERR_TYPES = {
    :permanent_quota_limit => { :type => 'PermanentLimitException', :message => 'Quota limit reached for this action', :api_code => 700, :http_code => 401 } 
  }

  def initialize(data)
    # added it here so that you can pass symbol error code to initializer
    data = ERR_TYPES[data] if data.is_a?(Symbol)

    data.each do |name, value|        
      send("#{name}=", value)  
    end
  end

  def error
    self.status = 'error'
    self.template= 'api/v1/api_outputs_handler/output'
    self
  end
end

这样,您可以将符号错误代码传递给初始化程序,如下所示:

handler = ApiOutputsHandler.new(:permanent_quota_limit)

您还可以更改对象在控制台中的外观,只需重新定义#inspect方法。在您的情况下,它可能如下所示:

def inspect
  "#<#{self.class.name} type: #{type}, message: #{message}>" # etc
end
于 2013-05-15T19:58:49.620 回答