如果我的问题很愚蠢,很抱歉,我花了很多时间寻找解决方案,但我没有找到。
我想创建一个没有数据库的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">你看到属性前面的arobase了吗?为什么我得到的是它而不是普通的:
#<ApiOutputsHandler:0x000000036a6cd0 type: "PermanentLimitException", message: "Quota limit reached for this action">谢谢你的帮忙!
发布于 2013-05-16 03:58:50
是的,有一种更好的方法。下面是我的做法:
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
endhttps://stackoverflow.com/questions/16571392
复制相似问题