### Example output of rapidoc_configuration_attributes Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md Example output inside a tag, showing the generated attribute string. ```text spec-url=/api/docs.json show-header=false font-size=largest ... theme=light bg-color=%23FFFFFF ``` -------------------------------- ### build_schema_and_examples(content) — schema and examples builder Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/render_response_extractor.md Builds a schema and examples from render content. Hash literals become schema-only with empty examples; non-hash content delegates to `process_non_hash_content`. Any StandardError is rescued, logged at debug level, and returns `[{}]`. ```ruby def build_schema_and_examples(content) if content.start_with?('{') [Utils.hash_to_json_schema(parse_hash_structure(content)), {}] else process_non_hash_content(content) end rescue StandardError => e Rails.logger.debug("Error building schema: #{e.message}") [{}] end ``` -------------------------------- ### build_array_model_schema_and_examples — plural model handling Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/render_response_extractor.md Builds schema and examples for a plural model token. Wraps the schema in an array and constructs examples by extracting each example's nested value for the singularized model name. ```ruby def build_array_model_schema_and_examples(maybe_a_model, klass, schema) examples = { maybe_a_model => { value: ActiveRecordExampleFinder.new(context: :outgoing).search(klass).values.map { |p| p.dig(:value, maybe_a_model.singularize.to_sym) } } } [{ type: "array", items: schema }, examples] end ``` -------------------------------- ### Example - fetch_fixture_examples with User class Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Example usage of fetch_fixture_examples with an outgoing context. It creates a finder instance and calls the method with a User class, returning a hash with fixture name 'luis' and nested user attributes. ```ruby finder = OasRails::ActiveRecordExampleFinder.new(context: :outgoing) finder.fetch_fixture_examples(klass: User) # => { luis: { value: { user: { name: "Luis", email: "luis@gmail.com" } } } } ``` -------------------------------- ### Using OasRails::ExtractedRouteConfig = OasRails::ExtractedRouteExtractor usage example with ignored_ and *_config parameter and output example included.term-vector.```jsona, Winston. Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/route_extractor.md This example shows how to configure and use the OasHostRouteExtractor usage example with a Ruby script that sets ignored_actions, clears cache, prints host_paths output and iterating over host_rubs.jsona, ```ruby config = OasRails.config ``` -------------------------------- ### prefix_path= normalization examples Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/configuration.md Example usage of prefix_path= showing normalization: "api" becomes "/api", "/v2" stays "/v2", and nil becomes "". ```ruby config.prefix_path = "api" # => @prefix_path == "/api" config.prefix_path = "/v2" # => @prefix_path == "/v2" config.prefix_path = nil # => @prefix_path == "" ``` -------------------------------- ### Full OasRails initializer example Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/configuration.md Full initializer example for OasRails. Place in config/initializers/oas_rails.rb. Shows all configuration options including info, servers, tags, api_path, layout, rapidoc settings, ignored_actions, include_mode, authentication, and default responses. ```ruby # config/initializers/oas_rails.rb OasRails.configure do |config| config.info.title = 'My API' config.info.version = '2.0.0' config.servers = [{ url: 'https://api.example.com', description: 'Production' }] config.tags = [{ name: 'Users', description: 'User operations' }] config.api_path = "/" config.layout = "application" config.rapidoc_theme = :snow config.rapidoc_configuration = { "theme" => "light", "bg-color" => "#FFF" } config.rapidoc_logo_url = "/logo.png" config.ignored_actions = ["projects", "users#new"] config.include_mode = :with_tags config.authenticate_all_routes_by_default = true config.security_schema = :bearer config.set_default_responses = true config.possible_default_responses = [:not_found, :unauthorized, :internal_server_error] config.response_body_of_unprocessable_entity = "Hash{ errors: Array }" end ``` -------------------------------- ### Example - clean_example_object with incoming context Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Example usage of clean_example_object with an incoming context. It removes the id and created_at keys (since they are excluded by default) and returns only the name key. ```ruby OasRails::ActiveRecordExampleFinder.new(context: :incoming) .clean_example_object(obj: { id: 1, name: "A", created_at: Time.now }) # => { name: "A" } ``` -------------------------------- ### fetch_factory_bot_examples with missing factory example Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Shows the result when the factory is missing, returning an empty hash due to rescued KeyError. ```ruby finder = OasRails::ActiveRecordExampleFinder.new results = finder.fetch_factory_bot_examples(klass: OrphanModel) # => {} (FactoryBot raised KeyError, rescued) ``` -------------------------------- ### Example: build_outgoing_schema with config override Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/esquema_builder.md Example of build_outgoing_schema with an explicit config override using OasRails.config(:internal). ```ruby internal_cfg = OasRails.config(:internal) schema = OasRails::Builders::EsquemaBuilder.build_outgoing_schema(klass: Report, config: internal_cfg) ``` -------------------------------- ### search under FactoryBot example Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Shows how to call search with a model class and the expected return format. ```ruby OasRails::ActiveRecordExampleFinder.new.search(User) # => { user1: { value: { user: { name: "Test User", email: "test@example.com", ... } } } } ``` -------------------------------- ### Example: build_incoming_schema with Post Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/esquema_builder.md Example usage of build_incoming_schema with a Post model. Shows that the resulting schema includes the title property but excludes the id property. ```ruby schema = OasRails::Builders::EsquemaBuilder.build_incoming_schema(klass: Post) schema["properties"].key?("title") # => true schema["properties"].key?("id") # => false (excluded) ``` -------------------------------- ### Example hash schema from RenderResponseExtractor Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/types.md Example produced by RenderResponseExtractor#build_schema_and_examples for render json: { token: "x", exp: "01-01-2026", user: { id: 1 } }. Shows symbol keys and nested structure. ```ruby { type: "object", properties: { token: { type: "string" }, exp: { type: "string" }, user: { type: "object", properties: { id: { type: "number" } }, required: [] } }, required: [] } ``` -------------------------------- ### Multiple render branches example Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/render_response_extractor.md Example showing extraction from a source with multiple render branches. The extractor returns one Response per render call, with status codes 201 and 422 and their corresponding descriptions. ```ruby src = <<~RUBY def create render json: @user, status: :created rescue render json: { errors: @user.errors.full_messages }, status: :unprocessable_entity end RUBY responses = OasRails::Extractors::RenderResponseExtractor.extract_responses_from_source(spec, source: src) # => [Response(201, "The request has been fulfilled and resulted in a new resource being created.", content...), # Response(422, "The server could not process the request due to semantic errors. Please check your input and try again.", content...)] ``` -------------------------------- ### Example: error handling with custom schema class Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/esquema_builder.md Example of error handling when build_incoming_schema is called with an invalid klass. Rescues ArgumentError and logs a warning. ```ruby begin OasRails::Builders::EsquemaBuilder.build_incoming_schema( klass: SomeNonModelKlass, model_to_schema_class: EasyTalk ) rescue ArgumentError => e logger.warn "Cannot build incoming schema: #{e.message}" end ``` -------------------------------- ### Example: build_outgoing_schema with Post Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/esquema_builder.md Example usage of build_outgoing_schema with a Post model. Shows that the resulting schema includes both the id and title properties. ```ruby schema = OasRails::Builders::EsquemaBuilder.build_outgoing_schema(klass: Post) schema["properties"].key?("id") # => true (primary key kept) schema["properties"].key?("title") # => true ``` -------------------------------- ### Fixtures example hash shape Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/types.md Example hash shape produced by `ActiveRecordExampleFinder#fetch_fixture_examples`. Keys are fixture names (e.g., `luis`). The hash is deep_symbolize_keys-processed. ```ruby { luis: { value: { user: { name: "Luis", email: "luis@gmail.com" } } } } # keys: fixture names ``` -------------------------------- ### search method implementation Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Dispatches to the appropriate example fetcher based on the detected test framework. Returns an empty hash for unknown frameworks. ```ruby def search(klass) case @utils.detect_test_framework when :factory_bot fetch_factory_bot_examples(klass: klass) when :fixtures fetch_fixture_examples(klass: klass) else {} end end ``` -------------------------------- ### Example usage of detect_test_framework Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/utils.md Shows how to use the detect_test_framework method in a case statement to handle different test frameworks. ```ruby case OasRails::Utils.detect_test_framework when :factory_bot then # build_stubbed_list path when :fixtures then # fixture file path else # no examples end ``` -------------------------------- ### Array models example hash shape Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/types.md Example hash shape produced by `ActiveRecordExampleFinder#build_array_model_schema_and_examples`. The `:value` is a wrapped list extracted from each example's `:value`. The hash is deep_symbolize_keys-processed. ```ruby { users: { value: [ { user: { ... } }, ... ] } } # wrapped list extracted from each example's :value ``` -------------------------------- ### handling empty search result example Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Demonstrates checking if the search result is empty and rendering a JSON note. ```ruby examples = OasRails::ActiveRecordExampleFinder.new.search(SomeModel) if examples.empty? render json: { note: "no examples — add FactoryBot or fixtures" } end ``` -------------------------------- ### active_record_class? usage examples Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/utils.md Example calls showing expected return values: true for a string class name, true for a class constant, and false for a non-ActiveRecord class. ```ruby OasRails::Utils.active_record_class?("User") # => true if User < ActiveRecord::Base OasRails::Utils.active_record_class?(User) # => true OasRails::Utils.active_record_class?(Object) # => false ``` -------------------------------- ### Example usage of rapidoc_theme Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md Shows the return value for a valid theme (:rails) and an invalid theme (:nonexistent). ```ruby OasRails::OasRailsHelper.new.rapidoc_theme(:rails) # => { "theme" => "light", "bg-color" => "#FFFFFF", "nav-bg-color" => "#101828", ... } OasRails::OasRailsHelper.new.rapidoc_theme(:nonexistent) # => {} ``` -------------------------------- ### FactoryBot example hash shape Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/types.md Example hash shape produced by `ActiveRecordExampleFinder#fetch_factory_bot_examples`. Keys are of the form `` (e.g., `user1`). The hash is deep_symbolize_keys-processed. ```ruby { user1: { value: { user: { name: "Test", email: "t@example.com" } } } } # keys: "" ``` -------------------------------- ### Example: convert a route and print its metadata Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_route_builder.md Shows how to find a Rails route by controller and action, build an OasRoute, and access its metadata fields such as verb, path, controller, method_name, docstring, source_string, and tags. ```ruby route = Rails.application.routes.routes.find { _1.defaults[:controller] == "posts" && _1.defaults[:action] == "show" } oas_route = OasRails::Builders::OasRouteBuilder.build_from_rails_route(route, config: OasRails.config) oas_route.verb # => "GET" oas_route.path # => "/posts/{id}" oas_route.controller # => "posts" oas_route.method_name # => "show" oas_route.docstring # => YARD::Docstring oas_route.source_string # => " def show\n render json: @post\n end\n" oas_route.tags # => [YARD::Tag("summary", ...), YARD::Tag("parameter", ...), ...] ``` -------------------------------- ### build_singular_model_schema_and_examples — singular model handling Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/render_response_extractor.md Builds schema and examples for a singular model reference. When no errors segment is present, uses the outgoing schema and searches for ActiveRecord examples. When errors are present (e.g., `render json: user.errors`), returns a fixed `{ success: Boolean, errors: { [key]: Array } }` shape, marked as a TODO not building the real schema. ```ruby def build_singular_model_schema_and_examples(_maybe_a_model, errors, klass, schema) if errors.nil? [schema, ActiveRecordExampleFinder.new(context: :outgoing).search(klass)] else # TODO: this is not building the real schema. [ { type: "object", properties: { success: { type: "boolean" }, errors: { type: "object", additionalProperties: { type: "array", items: { type: "string" } } } } }, {} ] end end ``` -------------------------------- ### Example of hash_to_json_schema Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/utils.md Demonstrates converting a hash with mixed value types to a JSON Schema object. ```ruby OasRails::Utils.hash_to_json_schema({ token: "abc123", count: 2, ok: true }) # => { type: "object", # properties: { token: { type: "string" }, count: { type: "number" }, ok: { type: "boolean" } }, # required: [] } ``` -------------------------------- ### Two named configurations example Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Shows how to define two named configurations (:public and :internal) in config/initializers/oas_rails.rb. Each block sets the info.title and api_path for the respective configuration. ```ruby # config/initializers/oas_rails.rb OasRails.configure(:public) do |config| config.info.title = "Public API" config.api_path = "/" end OasRails.configure(:internal) do |config| config.info.title = "Internal API" config.api_path = "/admin" end ``` -------------------------------- ### Example of status_to_integer Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/utils.md Shows conversion of various status inputs to integers, including symbols, numeric strings, and nil. ```ruby OasRails::Utils.status_to_integer(:unprocessable_entity) # => 422 (or 422 via :unprocessable_content on rack > 3.1) OasRails::Utils.status_to_integer("404") # => 404 OasRails::Utils.status_to_integer(nil) # => 200 ``` -------------------------------- ### Reading config for a build Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Shows how to pass a named config to OasRails.build and read a value from the resulting document. The example prints the title of the internal API document. ```ruby doc = OasRails.build(config: OasRails.config(:internal)) puts doc[:info][:title] # => "Internal API" ``` -------------------------------- ### host_routes method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/route_extractor.md Returns an array of OasCore::OasRoute objects for the host application, cached per config.name. The example shows how to call it and map the paths. ```ruby def host_routes(config:) @host_routes_cache ||= {} @host_routes_cache[config.name] ||= extract_host_routes(config:) end ``` ```ruby routes = OasRails::Extractors::RouteExtractor.host_routes(config: OasRails.config) routes.map(&:path) # => ["/users", "/users/{id}", ...] ``` -------------------------------- ### process_render_content(specification, content, status) — build response Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/render_response_extractor.md Builds an OasCore response by converting the status to an integer, wrapping the schema and examples in an outgoing ContentBuilder, and then constructing a ResponseBuilder with the code, description, and content. ```ruby def process_render_content(specification, content, status) schema, examples = build_schema_and_examples(content) status_int = Utils.status_to_integer(status) content = Builders::ContentBuilder.new(specification, :outgoing).with_schema(schema).with_examples(examples).build Builders::ResponseBuilder.new(specification).with_code(status_int).with_description(Utils.get_definition(status_int)).with_content(content).build end ``` -------------------------------- ### GET Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/endpoints.md Documentation for the single HTTP endpoint exposed by the OasRails engine, which serves both the HTML documentation page and the JSON OAS document. ```APIDOC ## GET ### Description Serves the OAS documentation page (HTML) and the OAS document (JSON) for the mounted OasRails engine. ### Method GET ### Endpoint (HTML page) or .json (OAS document) ### Parameters #### Query Parameters - **default[configuration]** (String) - Optional - Used when the mount option `default: { configuration: 'name' }` is set; selects which `OasRails::Configuration` builds and renders the docs. ### Response #### Success Response (200) - **HTML format** - RapiDoc UI page rendered from `app/views/oas_rails/oas_rails/index.html.erb` using layout `@config.layout`; loads `/oas-rails-assets/rapidoc-min.js` and configures the `` element; default `spec-url` equals `"#{request.script_name}.json"`. - **JSON format** - Complete OAS 3.1 document (openapi/version, info, servers, tags, paths, components) as JSON from `OasRails.build(config: @config).to_json`. #### Response Example (No explicit example provided in source.) #### Error Responses - **404** - Unknown path under the mounted engine (Rails default routing). ``` -------------------------------- ### prefix_path= setter with path normalization Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/configuration.md Setter for prefix_path. Normalizes the input: nil or empty becomes "", otherwise the value is guaranteed to start with "/" (prepends "/" if missing). ```ruby def prefix_path=(value) @prefix_path = if value.nil? || value.empty? "" else value.start_with?("/") ? value : "/#{value}" end end ``` -------------------------------- ### No renders yields 204 response Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/render_response_extractor.md Example showing that when the source contains no `render json:` call, the extractor returns a single 204 response with description "No content". ```ruby responses = OasRails::Extractors::RenderResponseExtractor.extract_responses_from_source(spec, source: "def ping\n head : ok\nend") # => [Response(204, "No content")] ``` -------------------------------- ### valid_api_route?(route, config:) — apply route filtering criteria Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/route_extractor.md A route is a candidate only when: the controller/action implement it (valid_route_implementation?), the controller is not a Rails default, the path starts with config.api_path, and the route is not ignored. ```ruby def valid_api_route?(route, config:) return false unless valid_route_implementation?(route) return false if RAILS_DEFAULT_CONTROLLERS.any? { |default| route.defaults[:controller].start_with?(default) } return false unless route.path.spec.to_s.start_with?(config.api_path) return false if ignore_custom_actions?(route, config:) true end ``` -------------------------------- ### Validation failure example Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Shows that an invalid include_mode value raises an ArgumentError immediately. The rescue block warns with the message "include_mode must be one of [:all, :with_tags, :explicit]". ```ruby begin OasRails.configure do |config| config.include_mode = :bogus end rescue ArgumentError => e warn e.message # "include_mode must be one of [:all, :with_tags, :explicit]" end ``` -------------------------------- ### fetch_factory_bot_examples method implementation Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Builds a stubbed record via FactoryBot, caches it, and formats the result. Rescues KeyError to return an empty hash. ```ruby def fetch_factory_bot_examples(klass:) klass_sym = @utils.class_to_symbol(klass) begin @factory_examples[klass_sym] = @factory_bot.build_stubbed_list(klass_sym, 1) if @factory_examples[klass_sym].nil? @factory_examples[klass_sym].each_with_index.to_h do |obj, index| ["#{klass_sym}#{index + 1}", { value: { klass_sym => clean_example_object(obj: obj.as_json) } }] end.deep_symbolize_keys rescue KeyError {} end end ``` -------------------------------- ### OasRails::Configuration class with initialize defaults Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/configuration.md Defines the per-documentation-instance settings object. Sets defaults for all options, including @name = :default, @mounted_path = "", @include_mode = :all, @autodiscover_request_body = true, @autodiscover_responses = true, @rapidoc_theme = :rails, and @rapidoc_configuration = {}. The prefix_path is initialized from ENV["RAILS_RELATIVE_URL_ROOT"] or Rails.application.config.relative_url_root. @swagger_version is inherited from OasCore::Configuration ("3.2.0"). ```ruby class Configuration < OasCore::Configuration attr_accessor :autodiscover_request_body, :autodiscover_responses, :ignored_actions, :rapidoc_theme, :layout, :source_oas_path, :rapidoc_configuration, :rapidoc_logo_url attr_reader :name, :route_extractor, :include_mode, :mounted_path, :prefix_path def initialize super @name = :default @mounted_path = "" self.prefix_path = ENV["RAILS_RELATIVE_URL_ROOT"] || Rails.application.config.relative_url_root || "" @route_extractor = Extractors::RouteExtractor @include_mode = :all @autodiscover_request_body = true @autodiscover_responses = true @ignored_actions = [] @layout = nil @rapidoc_theme = :rails @rapidoc_configuration = {} @rapidoc_logo_url = nil @source_oas_path = nil # TODO: implement # autodiscover_request_body # autodiscover_responses end end ``` -------------------------------- ### initialize(rails_route, config:) stores route and config Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_route_builder.md Constructor that assigns the given rails_route and config to instance variables. Both parameters are required; no defaults are provided. ```ruby def initialize(rails_route, config:) @rails_route = rails_route @config = config end ``` -------------------------------- ### Initialize ActiveRecordExampleFinder with dependency injection Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Defines the initialize method with keyword arguments for dependency injection, allowing test/mock control. The context parameter selects excluded columns based on incoming or outgoing. Defaults are provided for all dependencies. ```ruby def initialize(context: :incoming, utils: Utils, factory_bot: FactoryBot, erb: ERB, yaml: YAML, file: File, config: nil) @context = context @utils = utils @factory_bot = factory_bot @erb = erb @yaml = yaml @file = file @config = config @factory_examples = {} end ``` -------------------------------- ### fetch_fixture_examples - Load and transform fixture data Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Loads a fixture YAML file from test/fixtures/.yml, evaluates it as ERB, and parses it with YAML.safe_load allowing Symbol, ActiveSupport::HashWithIndifferentAccess, and Time. Returns an empty hash if the file is missing (Errno::ENOENT). The result is transformed into a hash keyed by fixture name with nested value and class-downcase keys, then deep-symbolized. ```ruby def fetch_fixture_examples(klass:) fixture_file = Rails.root.join('test', 'fixtures', "#{klass.to_s.pluralize.downcase}.yml") begin erb_result = @erb.new(@file.read(fixture_file)).result fixture_data = @yaml.safe_load( erb_result, aliases: true, permitted_classes: [Symbol, ActiveSupport::HashWithIndifferentAccess, Time] ).with_indifferent_access rescue Errno::ENOENT return {} end fixture_data.transform_values { |attributes| { value: { klass.to_s.downcase => clean_example_object(obj: attributes) } } }.deep_symbolize_keys end ``` -------------------------------- ### Create finder with outgoing context and search Post Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/active_record_example_finder.md Shows how to instantiate the finder with context :outgoing and call search on a model class. This is used internally by RenderResponseExtractor. ```ruby finder = OasRails::ActiveRecordExampleFinder.new(context: :outgoing) finder.search(Post) ``` -------------------------------- ### OasRails::Engine routes definition Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/engine.md Defines the engine's single route mapping GET requests to OasRails::OasRailsController#index. ```ruby OasRails::Engine.routes.draw do get '(.:format)', to: 'oas_rails#index' end ``` -------------------------------- ### OasRails.configure Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Creates a new OasRails::Configuration instance, yields it to the provided block, and registers it under the given name. The configuration can be retrieved later using the name. ```APIDOC ## OasRails.configure ### Description Creates a new `OasRails::Configuration` instance, yields it to the provided block, and registers it under the given name. The configuration can be retrieved later using the name. ### Method configure ### Signature `OasRails.configure(name = :default) { |config| ... }` ### Parameters - `name` (Symbol) - Optional - Registry key for the new configuration. Defaults to `:default`. - block (`yield cfg`) - Required - Mutates the `Configuration` instance before it is stored. ### Return Type The registered `OasRails::Configuration` instance (stored in the class-level `@configs` hash). ### Behavior Creates a `Configuration`, yields it to the block, stamps `@name`, and registers it. If the same name is configured twice, the later call overwrites the earlier entry. ### Throws Any exception raised inside the block propagates; `ArgumentError` if a setter validates (see [api-reference/configuration.md](api-reference/configuration.md)). ### Example — two named configurations ```ruby # config/initializers/oas_rails.rb OasRails.configure(:public) do |config| config.info.title = "Public API" config.api_path = "/" end OasRails.configure(:internal) do |config| config.info.title = "Internal API" config.api_path = "/admin" end ``` ### Example — validation failure surfaces immediately ```ruby begin OasRails.configure do |config| config.include_mode = :bogus end rescue ArgumentError => e warn e.message # "include_mode must be one of [:all, :with_tags, :explicit]" end ``` ``` -------------------------------- ### RAILS_DEFAULT_CONTROLLERS constant Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/route_extractor.md Defines the list of controller prefixes whose routes are never documented. Routes whose controller starts with any of these prefixes are excluded from the OAS document. ```ruby RAILS_DEFAULT_CONTROLLERS = %w[ rails action_mailbox action_cable active_storage turbo/native ].freeze ``` -------------------------------- ### Building with an explicit named config and error handling Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Shows building with a named configuration (:internal) and rescuing RuntimeError to return an error JSON response. ```ruby internal = OasRails.config(:internal) begin doc = OasRails.build(config: internal) render json: doc.to_json, status: :ok rescue RuntimeError => e render json: { error: e.message }, status: :internal_server_error end ``` -------------------------------- ### source_string reader fetches method source Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_route_builder.md Uses MethodSource-style introspection to get the raw Ruby source of the action method. Raises NameError if the controller constant is missing. ```ruby def source_string controller_class.constantize.instance_method(method).source end ``` -------------------------------- ### OasRails.build Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Documentation for the OasRails.build method, the primary entry point for generating OpenAPI documentation from routes and an optional source OAS file. ```APIDOC ## OasRails.build ### Description Builds the OpenAPI Specification (OAS) document from the configured routes and optional source OAS file. This is the main entry point for generating API documentation. ### Method build ### Endpoint OasRails.build(config: OasRails.config) ### Parameters #### Parameters - **config** (OasRails::Configuration) - Optional - The configuration to build documentation from. Defaults to `OasRails.config` (the `:default` configuration). ### Request Example ```ruby spec = OasRails.build spec.to_json # => '{"openapi":"3.1.0", ...}' ``` ### Response #### Success Response - Returns the built OAS document (a Hash) as the return value of `OasCore.build(...)`. #### Response Example ```ruby internal = OasRails.config(:internal) begin doc = OasRails.build(config: internal) render json: doc.to_json, status: :ok rescue RuntimeError => e render json: { error: e.message }, status: :internal_server_error end ``` ### Error Handling - **RuntimeError** - Raised if the source OAS file cannot be read or parsed. ``` -------------------------------- ### clear_cache method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/route_extractor.md Clears the class-level caches. If a config is provided, only that config's entries are deleted; otherwise all caches are reset. The example shows invalidating the cache after changing config in tests/development. ```ruby def clear_cache(config: nil) if config @host_routes_cache&.delete(config.name) @host_paths_cache&.delete(config.name) else @host_routes_cache = nil @host_paths_cache = nil end end ``` ```ruby config.ignored_actions = ["projects"] OasRails::Extractors::RouteExtractor.clear_cache(config: config) ``` -------------------------------- ### host_routes_by_path method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/route_extractor.md Returns the subset of host routes whose path exactly matches the given path. Uses the same cache as host_routes. ```ruby def host_routes_by_path(path, config:) @host_routes_cache ||= {} @host_routes_cache[config.name] ||= extract_host_routes(config:) @host_routes_cache[config.name].select { |r| r.path == path } end ``` -------------------------------- ### rapidoc_configuration_defaults method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md Returns a hash of default RapiDoc configuration attributes. The spec-url is computed as "#{request.script_name}.json" so the UI fetches the OAS JSON at the mount path. ```ruby def rapidoc_configuration_defaults { "spec-url" => "#{request.script_name}.json", "show-header" => "false", "font-size" => "largest", "show-method-in-nav-bar" => "as-colored-text", "nav-item-spacing" => "relaxed", "allow-spec-file-download" => "true", "schema-style" => "table", "sort-tags" => "true", "persist-auth" => "true" } end ``` -------------------------------- ### class_to_symbol: Convert class to underscored symbol Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/utils.md Converts a class name to a symbol using ActiveSupport's underscore inflection. For example, User becomes :user and Blog::Post becomes :blog/post. ```ruby def class_to_symbol(klass) klass.name.underscore.to_sym end ``` -------------------------------- ### rapidoc_configuration_attributes method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md Merges defaults, theme attributes, and user configuration, then maps to HTML attribute fragments with HTML-escaped values, joined by spaces. Later values override earlier ones. ```ruby def rapidoc_configuration_attributes rapidoc_configuration_defaults.merge( rapidoc_theme(@config.rapidoc_theme), @config.rapidoc_configuration ).map { |k, v| %(#{k}=#{ERB::Util.html_escape(v)}) }.join(' ') end ``` -------------------------------- ### clean_route method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/route_extractor.md Cleans a raw Rails route path spec by removing the '(.:format)' suffix and converting ':param' segments to '{param}' OpenAPI style. Example: '/users/:id(.:format)' becomes '/users/{id}'. ```ruby def clean_route(route) route.gsub('(.:format)', '').gsub(/:\w+/) { |match| "{#{match[1..]}}" } end ``` -------------------------------- ### Basic call to OasRails.build Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Shows a minimal usage: calling OasRails.build with no arguments and converting the result to JSON. ```ruby spec = OasRails.build spec.to_json # => '{"openapi":"3.1.0", ...}' ``` -------------------------------- ### Create a post with curl Source: https://github.com/a-chacon/oas_rails/blob/main/test/dummy/README_OAS.md Creates a new post via the public API. Requires the OasRails engine mounted at /api/docs with the public configuration. ```bash curl -X POST -H "Content-Type: application/json" -d '{"post": {"title": "Hello","body": "World","published": true}}' http://localhost:3000/posts ``` -------------------------------- ### path reader combines config prefix and cleaned route Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_route_builder.md Builds the full route path by prepending the configured prefix to the cleaned route path. Returns a string such as "/api/posts/{id}". ```ruby def path @config.prefix_path + @config.route_extractor.clean_route(@rails_route.path.spec.to_s) end ``` -------------------------------- ### extract_responses_from_source method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/render_response_extractor.md Main entry point for the extractor. Parses the controller action's source string for `render json:` calls and builds OasCore Response objects. Returns a single 204 response with description "No content" when no render calls are found. ```ruby def extract_responses_from_source(specification, source:) render_calls = extract_render_calls(source) return [Builders::ResponseBuilder.new(specification).with_description("No content").with_code(204).build] if render_calls.empty? render_calls.map { |render_content, status| process_render_content(specification, render_content.strip, status) } end ``` -------------------------------- ### Mutating config in an initializer Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Shows how to set a configuration option on a named config instance. Here, the :public config's rapidoc_theme is set to :snow. ```ruby OasRails.config(:public).rapidoc_theme = :snow ``` -------------------------------- ### Generate oas_rails initializer Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/engine.md Command to generate the OasRails initializer. The output shows the created file path. ```bash rails generate oas_rails:config # create config/initializers/oas_rails.rb ``` -------------------------------- ### rapidoc_theme method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md Returns the theme attributes for a given theme name, or an empty hash for unknown names (no error). ```ruby def rapidoc_theme(theme_name) THEMES[theme_name] || {} end ``` -------------------------------- ### Setting include_mode to :with_tags Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/configuration.md Shows how to set include_mode to :with_tags and confirms the assigned value. The setter accepts :all, :with_tags, or :explicit. ```ruby config.include_mode = :with_tags puts config.include_mode # => :with_tags ``` -------------------------------- ### host_paths method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/route_extractor.md Returns a unique, sorted array of path strings from all host routes. Cached per config.name. ```ruby def host_paths(config:) @host_paths_cache ||= {} @host_paths_cache[config.name] ||= host_routes(config:).map(&:path).uniq.sort end ``` -------------------------------- ### OasRails.build method implementation Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md The build method clears the cache (in non-production), sets OasCore.config, extracts host routes, optionally reads a source OAS file, and delegates to OasCore.build. Returns the built OAS document (a Hash). ```ruby def build(config: OasRails.config) clear_cache(config:) OasCore.config = config host_routes = config.route_extractor.host_routes(config:) oas_source = config.source_oas_path ? read_source_oas_file(config:) : {} OasCore.build(host_routes, oas_source: oas_source) end ``` -------------------------------- ### get_definition: Look up HTTP status definition Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/utils.md Returns the canned description for a given status code from HTTP_STATUS_DEFINITIONS, or a fallback message with the status code if not found. The fallback string is "Definition not found for status code #{status_code}". ```ruby def get_definition(status_code) HTTP_STATUS_DEFINITIONS[status_code] || "Definition not found for status code #{status_code}" end ``` -------------------------------- ### Mount OasRails::Engine with configuration defaults Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/engine.md Mounts the OasRails engine at two paths with different configuration defaults, selecting named OasRails::Configuration objects. ```ruby mount OasRails::Engine => '/api/docs', default: { configuration: 'public' }, as: 'public_oas' mount OasRails::Engine => '/internal/api/docs', default: { configuration: 'internal' }, as: 'internal_oas' ``` -------------------------------- ### List posts with curl Source: https://github.com/a-chacon/oas_rails/blob/main/test/dummy/README_OAS.md Lists all posts via the public API. Uses the PostsController index action. ```bash curl http://localhost:3000/posts ``` -------------------------------- ### Fetch admin reports with curl Source: https://github.com/a-chacon/oas_rails/blob/main/test/dummy/README_OAS.md Fetches admin reports from the internal API. Only available in the internal configuration. ```bash curl http://localhost:3000/admin/reports ``` -------------------------------- ### Handle OAS docs index action Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/endpoints.md Controller action that renders the RapiDoc HTML page or returns the OAS 3.1 JSON document. The JSON response is built on every request unless in production, where RouteExtractor caches persist. ```ruby def index respond_to do |format| format.html { render "index", layout: @config.layout } format.json do render json: OasRails.build(config: @config).to_json, status: :ok end end end ``` -------------------------------- ### OasRails.config Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Returns the registered OasRails::Configuration instance for the given name, or lazily creates a new one with default values if not registered. ```APIDOC ## OasRails.config ### Description Returns the registered OasRails::Configuration instance for the given name, or lazily creates a new one with default values if not registered. ### Method config ### Parameters - **name** (Symbol) - Optional - Name of the configuration to read. Default: `:default` ### Return Type `OasRails::Configuration` ### Example ```ruby OasRails.config(:public).rapidoc_theme = :snow ``` ### Example ```ruby doc = OasRails.build(config: OasRails.config(:internal)) puts doc[:info][:title] # => "Internal API" ``` ``` -------------------------------- ### build method creates an OasCore::OasRoute Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_route_builder.md Creates a new OasCore::OasRoute using values from the private readers. Returns an OasCore::OasRoute, likely used by the documentation generator. ```ruby def build OasCore::OasRoute.new( controller: controller, method_name: method, verb: verb, path: path, docstring: docstring, source_string: source_string, tags: tags ) end ``` -------------------------------- ### OasRails::OasRailsController implementation Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/engine.md Controller for the OasRails engine. The index action renders the HTML template with the configured layout or returns the OpenAPI JSON built by OasRails.build. The resolve_config before_action reads the configuration name from params (defaulting to :default) and loads it via OasRails.config. ```ruby class OasRailsController < ApplicationController # Include URL help if the layout is a user-customized layout. include Rails.application.routes.url_helpers before_action :resolve_config def index respond_to do |format| format.html { render "index", layout: @config.layout } format.json do render json: OasRails.build(config: @config).to_json, status: :ok end end end private def resolve_config config_name = params.dig("default", "configuration")&.to_sym || :default @config = OasRails.config(config_name) end end ``` -------------------------------- ### Serve static assets with Rack::Static in OasRails::Engine Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/endpoints.md Registers Rack::Static middleware on the engine's app middleware stack to serve static assets from the /oas-rails-assets path. The root is set to the engine's public directory, which contains the only shipped asset, rapidoc-min.js. ```ruby config.app_middleware.use( Rack::Static, urls: ["/oas-rails-assets"], root: OasRails::Engine.root.join("public") ) ``` -------------------------------- ### Deprecated `mounted_path=` setter Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/configuration.md Deprecated setter for the `mounted_path` option. Writing to it emits a deprecation warning and ignores the value; it is not used anymore. ```ruby def mounted_path=(_value) warn "[DEPRECATION] `mounted_path` option is deprecated and will be removed in a future release. It is not used anymore." end ``` -------------------------------- ### OasRails.config method implementation Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md Defines the config method that lazily creates and returns a Configuration instance for a given name. The default name is :default. An unregistered name is not an error; a new config is created in place. ```ruby def config(name = :default) @configs ||= {} @configs[name] ||= Configuration.new end ``` -------------------------------- ### Usage in the view (ERB) Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md ERB template that renders a element with the configuration attributes and optionally a nav-logo image. ```erb > <% if rapidoc_logo_url %> <% end %> ``` -------------------------------- ### rapidoc_configuration_attributes Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md Returns a string of HTML attribute fragments for the RapiDoc element. It merges defaults, theme attributes, and user configuration, with later values taking precedence. ```APIDOC ## `rapidoc_configuration_attributes` ### Description Merges the default configuration with theme attributes and user-provided configuration, then returns them as HTML attribute fragments. The values are HTML-escaped and joined by spaces. ### Method `rapidoc_configuration_attributes` ### Parameters None. ### Return Type `String` ### Example ```ruby def rapidoc_configuration_attributes rapidoc_configuration_defaults.merge( rapidoc_theme(@config.rapidoc_theme), @config.rapidoc_configuration ).map { |k, v| %(#{k}=#{ERB::Util.html_escape(v)}) }.join(' ') end ``` ``` -------------------------------- ### rapidoc_logo_url method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md Returns the configured logo URL from @config.rapidoc_logo_url, used to conditionally render the nav-logo slot image. ```ruby def rapidoc_logo_url @config.rapidoc_logo_url end ``` -------------------------------- ### rapidoc_configuration_defaults Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails_helper.md Returns the default RapiDoc configuration attributes as a hash. The `spec-url` is dynamically set to `#{request.script_name}.json`. ```APIDOC ## `rapidoc_configuration_defaults` ### Description Returns a hash of default RapiDoc configuration attributes used by the engine's layout. The `spec-url` is computed from the current request's script name. ### Method `rapidoc_configuration_defaults` ### Parameters None. ### Return Type `Hash` ### Example ```ruby def rapidoc_configuration_defaults { "spec-url" => "#{request.script_name}.json", "show-header" => "false", "font-size" => "largest", "show-method-in-nav-bar" => "as-colored-text", "nav-item-spacing" => "relaxed", "allow-spec-file-download" => "true", "schema-style" => "table", "sort-tags" => "true", "persist-auth" => "true" } end ``` ``` -------------------------------- ### OasRails.configure method source Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_rails.md The implementation of OasRails.configure. It creates a Configuration, yields it to the block, stamps the name, and registers it in the class-level @configs hash. If the same name is configured twice, the later call overwrites the earlier entry. ```ruby def configure(name = :default) cfg = Configuration.new yield cfg cfg.instance_variable_set(:@name, name) @configs ||= {} @configs[name] = cfg end ``` -------------------------------- ### build_from_rails_route class method Source: https://github.com/a-chacon/oas_rails/blob/main/_autodocs/api-reference/oas_route_builder.md Class method that creates a new OasRouteBuilder instance and calls build. Takes a Rails route and configuration, returns an OasCore::OasRoute. ```ruby def self.build_from_rails_route(rails_route, config:) new(rails_route, config:).build end ```