抱歉,如果我的问题很愚蠢,但是我花了很多时间搜索解决方案,但没有找到。
我想创建一个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">
感谢您的帮助!