Add copy button to your code blocks

rails app:template LOCATION='https://perron.railsdesigner.com/library/copyable-code-processor/template.rb'

This snippet adds a processor to add a copy-button to your code blocks (pre-tags).

As this processor is powered by Attractive.js, make sure to follow its installation instructions.

It is unstyled so you need to bring your own CSS. For an example of one using Tailwind CSS, refer to the processor used on this site.

Template source

create_file "app/processors/copyable_code_processor.rb", <<~RUBY
  def process
    @html.css("pre").each do |pre|
      next if skippable? pre

      id = "pre_#{Random.hex(4)}"

      button = Nokogiri::XML::Node.new("button", @html)
      button["type"] = "button"
      button["data-action"] = "copy"
      button["data-target"] = "##{id}"
      button.content = "Copy"

      pre["id"] = id
      pre.add_previous_sibling(button)
    end
  end

  private

  def skippable?(pre)
    # add when the processor should skip this pre-element, e.g.
    # `pre["lang"] == "console"`
  end
end