Class: DocsUI::Example

Inherits:
Phlex::HTML
  • Object
show all
Defined in:
app/components/docs_ui/example.rb

Overview

A multi-language code group: the same example shown in several languages, with tabs to switch. The chosen language is a GLOBAL sticky preference (localStorage via the docs-nav controller) — pick Ruby once and every code group on this and future pages shows Ruby, falling back to an available language when a group doesn't have the chosen one.

render DocsUI::Example.new do |ex|
ex.code(:ruby, filename: "client.rb") do
  <<~RUBY
    Anthropic.messages.create(model: "claude-opus-4-8", ...)
  RUBY
end
ex.code(:python, filename: "client.py") do
  <<~PY
    client.messages.create(model="claude-opus-4-8", ...)
  PY
end
end

With one snippet it degrades to a plain DocsUI::Code (no tabs). With JS off the first language shows and the rest are visible below it (progressive enhancement — no content is hidden without JS).

Instance Method Summary collapse

Constructor Details

#initializeExample

Returns a new instance of Example.



27
28
29
# File 'app/components/docs_ui/example.rb', line 27

def initialize
  @snippets = []
end

Instance Method Details

#code(lang, filename: nil, lexer: nil, label: nil) ⇒ Object

Collect one language's snippet. lang is the language token (e.g. :ruby, :python, :go) — Docs::Code resolves it against Rouge's full registry + the configured aliases, so any language works. The tab label comes from the configured language_labels (else the token capitalized), or an explicit label: override (used by RequestExample so a client carries its own tab name). filename/lexer are optional; lexer defaults to the language token. The block returns the source.



38
39
40
41
42
43
44
45
46
47
48
# File 'app/components/docs_ui/example.rb', line 38

def code(lang, filename: nil, lexer: nil, label: nil)
  token = lang.to_sym
  @snippets << {
    lang: token,
    label: label || DocsKit.configuration.language_labels.fetch(token, token.to_s.capitalize),
    filename: filename,
    lexer: lexer || token,
    source: yield.to_s
  }
  nil
end

#view_template {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'app/components/docs_ui/example.rb', line 50

def view_template
  yield self if block_given?
  return if @snippets.empty?
  return render_single if @snippets.one?

  div(
    class: "not-prose my-4",
    data: { docs_nav_target: "codeGroup" }
  ) do
    language_tabs
    snippet_panels
  end
end