Module: Meta::Rails

Defined in:
lib/meta/rails.rb

Defined Under Namespace

Modules: Plugin

Class Method Summary collapse

Class Method Details

.setupObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/meta/rails.rb', line 8

def self.setup
  # 第一步,为 ActionController 添加一个新的 Renderer
  ActionController::Renderers.add :json_on_schema do |obj, options|
    options = options.dup
    status = options.delete(:status) || 200
    scope = options.delete(:scope) || :all

    route_definitions = self.class.route_definitions
    route_definition = route_definitions[[self.class, params[:action].to_sym]]
    raise '未绑定 Route 定义' unless route_definition

    meta_definition = route_definition.meta
    raise '未提供 status 宏定义' unless meta_definition[:responses] && meta_definition[:responses][status]

    render_schema = meta_definition[:responses][status]
    str = render_schema.filter(obj, execution: self, stage: :render, scope: scope)
    render json: str, **options
  rescue JsonSchema::ValidationErrors => e
    raise Errors::RenderingInvalid.new(e.errors)
  end
end