Skip to content

Instantly share code, notes, and snippets.

@tcannonfodder
Created January 12, 2026 00:26
Show Gist options
  • Select an option

  • Save tcannonfodder/216a47a276ad21f1ee95f71dd9ce6b39 to your computer and use it in GitHub Desktop.

Select an option

Save tcannonfodder/216a47a276ad21f1ee95f71dd9ce6b39 to your computer and use it in GitHub Desktop.
CableCar template renderer
# frozen_string_literal: true
class CableCarTemplate
attr_accessor :source
def initialize(&block)
self.source = block
end
def render_in(view_context)
source.call
view_context.controller.render(
cable_ready: view_context.cable_car
)
end
def format
:json
end
def self.call(template, source = nil)
src = source || template.source
<<~RUBY
__cablecar_template__ = CableCarTemplate.new do
#{src}
end
__cablecar_template__.render_in(self).to_s
RUBY
end
end
# frozen_string_literal: true
dialog_id = dom_id(@organization_deal, :new_update)
html_string = controller.render_to_string(ExampleComponent.new(
open: true,
id: dialog_id
))
cable_car.append(
html: html_string,
selector: "#example",
)
## ...
initializer("cable_ready.template_renderer") do
ActiveSupport.on_load :action_view do
ActionView::Template.register_template_handler :cablecar, CableCarTemplate
end
end
@tcannonfodder
Copy link
Author

  • To try to clean up controllers, keep it lean, handle a variety
    of rendering variants/complexity, and fit into the larger Rails
    MVC flow; we should have a template handler for CableReady
  • CableCarTemplate uses Rails' render_in support to render the
    object using the given view_context.
    • Instances of the object require a block to be given, which acts as
      the source of the template
    • When render_in is called, we make sure to call the source so
      that it is evaluated, then we reach back into the view context's
      controller to use the predefined renderer from CableReady, to
      keep in line with the main app itself
  • The CableCarTemplate.call method takes in the template/source,
    coalesces it into a src that we can pass into an instance of
    CableCarTemplate, which we then call render_in using the
    ActionView context
  • The handler is registered as :cablecar, so the file format would
    be [template].cable_ready.cablecar
    • While a bit messy, this follows the convention of jbuilder,
      which makes it clear what renderer is being used

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment