Module: Deimos::Utils::SchemaControllerMixin
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/deimos/utils/schema_controller_mixin.rb
Overview
Mixin to automatically decode schema-encoded payloads when given the correct content type, and provide the `render_schema` method to encode the payload for responses.
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
-
#decode_schema ⇒ Object
Decode the payload with the parameters.
-
#parse_namespace(type) ⇒ Array<String, String>
Get the namespace from either an existing instance variable, or tease it out of the schema.
-
#render_schema(payload, schema: nil, namespace: nil) ⇒ Object
Render a hash into a payload as specified by the configured schema and namespace.
- #schema_format? ⇒ Boolean
Instance Method Details
#decode_schema ⇒ Object
Decode the payload with the parameters.
97 98 99 100 101 102 103 104 105 106 107 108 |
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 97 def decode_schema namespace, schema = parse_namespace(:request) decoder = Deimos.schema_backend(schema: schema, namespace: namespace) @payload = decoder.decode(request.body.read).with_indifferent_access @payload.each do |key, value| Deimos.config.tracer&.set_tag("body.#{key}", value) end if Deimos.config.schema.use_schema_classes @payload = Utils::SchemaClass.instance(@payload, schema, namespace) end request.body.rewind if request.body.respond_to?(:rewind) end |
#parse_namespace(type) ⇒ Array<String, String>
Get the namespace from either an existing instance variable, or tease it out of the schema.
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 78 def parse_namespace(type) namespace = self.class.namespaces[type] schema = self.class.schema_mapping[params['action']][type] if schema.nil? raise "No #{type} schema defined for #{params[:controller]}##{params[:action]}!" end if namespace.nil? last_period = schema.rindex('.') namespace, schema = schema.split(last_period) end if namespace.nil? || schema.nil? raise "No request namespace defined for #{params[:controller]}##{params[:action]}!" end [namespace, schema] end |
#render_schema(payload, schema: nil, namespace: nil) ⇒ Object
Render a hash into a payload as specified by the configured schema and namespace.
112 113 114 115 116 117 118 |
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 112 def render_schema(payload, schema: nil, namespace: nil) namespace, schema = parse_namespace(:response) if !schema && !namespace encoder = Deimos.schema_backend(schema: schema, namespace: namespace) encoded = encoder.encode(payload.to_h, topic: "#{namespace}.#{schema}") response.headers['Content-Type'] = encoder.class.content_type send_data(encoded) end |
#schema_format? ⇒ Boolean
71 72 73 |
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 71 def schema_format? request.content_type == Deimos.schema_backend_class.content_type end |