Phlex appends strings

Understanding how Phlex handles string concatenation

When I evaluate code libraries, I like to open it up and get a sense of what it does at its very core. At the heart of Phlex is a string that Phlex appends HTML to for rendering in the browser. That string is named buffer, which is defaulted to +"".

# frozen_string_literal: true

class Phlex::SGML
  # ...
  def call(buffer = +"", context: {}, fragments: nil, &)
    state = Phlex::SGML::State.new(
        user_context: context,
        output_buffer: buffer,
        fragments: fragments&.to_set,
    )

    internal_call(parent: nil, state:, &)

    state.output_buffer << state.buffer
  end
  # ...
end

What is +""?

I never bothered to understand what +"" meant in Ruby until I looked under the hood of Phlex. You know that annoying # frozen_string_literal: true you see at the top of Ruby files? That tells Ruby that you can’t modify the string in place with operators like "fizz".upcase! or "fizz".concat("buzz").

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