Render Phlex Components from Rails Console

A handy way to render & debug basic components in isolation

While putting together the Phlex on Rails course, I wanted a way to render HTML components from rails console so I could see the resulting HTML outside of a browser and have less distrctions for the viewers.

That means I can do this from rails console:

server(dev)> render Components::PageTitleComponent.new(title: "Hi")
<!-- Before Components::PageTitleComponent -->
<div class="flex flex-col">
  <h1 class="font-semibold text-4xl flex flex-row items-center">Hi</h1>
</div>

The code

Create the ./config/initializers/console.rb file and drop in the following code:

# config/initializers/console.rb
Rails.application.configure do
  # This block only runs when you're in the Rails console (rails c)
  console do
    # TOPLEVEL_BINDING.eval('self') gets the main object in the console
    # We're extending it with a new module to add custom methods
    TOPLEVEL_BINDING.eval('self').extend(
      Module.new do
        # Add your helper methods in here.
        def render(*args, layout: false, **kwargs)
          Rails.logger.silence do
            html = ApplicationController.renderer.render(*args, layout: layout, **kwargs)
            Nokogiri::HTML.fragment(html).to_xhtml(indent: 2)
          end
        end
      end
    )
  end
end

There’s no great “official way” to add helpers to Rails console, so a lot of it looks hack-ish up until everything inside the Module.new block.

Whew, that took a while to figure out and LLMs led me astray. Ok, now I’m going to get back to shooting the Component Fundamentals unit in the Phlex on Rails video course.

Do you want to learn Phlex 💪 and enjoy these code examples?

Support Beautiful Ruby by pre-ordering the Phlex on Rails video course.

Order the Phlex on Rails video course for $379 $289