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 |
# 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 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.
106 107 108 109 110 111 112 |
# File 'lib/deimos/utils/schema_controller_mixin.rb', line 106 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, 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 |