Module: RouteSchemer

Extended by:
ActiveSupport::Concern
Defined in:
lib/route_schemer.rb,
lib/route_schemer/version.rb,
lib/route_schemer/route_schemer.rb,
lib/route_schemer/errors/request_schemer_error.rb

Overview

A module for JSON schema validation in Rails controllers. Provides methods for validating request and response parameters against JSON schemas. This module is automatically included in Rails controllers through the RouteSchemer::Engine.

Examples:

Validating request parameters in a controller

def create
  params = validated_params(schema: MyRouteSchemer.create_request_schema)
  # ...
end

Defined Under Namespace

Classes: Engine, RequestSchemerError

Constant Summary collapse

VERSION =
"0.2.0"

Instance Method Summary collapse

Instance Method Details

#fetch_schema_object(schema) ⇒ JSONSchemer::Schema

Get a JSONSchemer object for the provided schema

Parameters:

  • schema (Hash)

    the JSON schema to validate against

Returns:

  • (JSONSchemer::Schema)

    the JSONSchemer object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/route_schemer/route_schemer.rb', line 39

def fetch_schema_object(schema)
  JSONSchemer.schema(
    schema,
    before_property_validation: proc do |data, property, property_schema, _|
      value = data[property]
      case property_schema["type"]
      when "integer"
        data[property] = value.to_i if value.is_a?(String) && value.match?(/^\d+$/)
      when "number"
        data[property] = value.to_f if value.is_a?(String) && value.match?(/^[-+]?[0-9]*\.?[0-9]+$/)
      end
    end
  )
end

#schema_for_current_action(request) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/route_schemer/route_schemer.rb', line 26

def schema_for_current_action(request)
  # Derive the associated RouteSchemer class (e.g., FooController -> FooRouteSchemer)
  route_schemer_class = "#{controller_path.camelize}RouteSchemer".constantize
  schema_method_name = request ? "#{action_name}_request_schema" : "#{action_name}_response_schema"
  # Look up the schema method on the RouteSchemer class
  return route_schemer_class.public_send(schema_method_name) if route_schemer_class.respond_to?(schema_method_name)

  nil
end

#validated_params(schema: nil, params: nil, request: true, permit: true) ⇒ Object

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
22
23
24
# File 'lib/route_schemer/route_schemer.rb', line 15

def validated_params(schema: nil, params: nil, request: true, permit: true)
  # Default to dynamically determined schema and params if not provided
  schema ||= schema_for_current_action(request)
  raise ArgumentError, "No schema defined for validation" unless schema

  params ||= self.params

  data = request ? validate_request(schema, params) : validate_response(schema, params)
  permit ? @permitted_params || permitted_params(schema, data) : data
end