当我创建自动记录的API规范时,我遇到了将复杂对象(ActiveRecord for ex。)传递给swagger-docs / {的 param 函数的问题{3}},因为它只需要简单的类型(字符串,整数,...)。
我用下一个元编程红宝石技巧解决了这个问题:
class Swagger::Docs::SwaggerDSL
def param_object(klass, params={})
klass_ancestors = eval(klass).ancestors.map(&:to_s)
if klass_ancestors.include?('ActiveRecord::Base')
param_active_record(klass, params)
end
end
def param_active_record(klass, params={})
remove_attributes = [:id, :created_at, :updated_at]
remove_attributes += params[:remove] if params[:remove]
test = eval(klass).new
test.valid?
eval(klass).columns.each do |column|
unless remove_attributes.include?(column.name.to_sym)
param column.name.to_sym,
column.name.to_sym,
column.type.to_sym,
(test.errors.messages[column.name.to_sym] ? :required : :optional),
column.name.split('_').map(&:capitalize).join(' ')
end
end
end
end
现在我可以将复杂对象的 param_object 用作简单类型的 param :
swagger_api :create do
param :id, :id, :integer, :required, "Id"
param_object('Category')
end
Git fork here: