marcoroth / turbo_power-rails

Power-pack for Turbo Streams
MIT License
277 stars 9 forks source link

Method Chaining #39

Open rickychilcott opened 11 months ago

rickychilcott commented 11 months ago

This for this gem, it's making my cable_ready migration possible without totally re-writing. Would you be interested in adding method chaining? Similar to cable_car from cable_ready?

I worked this out:

class ApplicationController < ActionController::Base
  def stream_car
    StreamCar.new(method(:turbo_stream))
  end

  class StreamCar
    def initialize(meth)
      @meth = meth
      @buffer = ActiveSupport::SafeBuffer.new
    end

    def to_s
      @buffer.to_s
    end

    def to_str
      @buffer.to_str
    end

    def method_missing(name, *args, **kwargs)
      @buffer << @meth.call.send(name, *args, **kwargs).html_safe

      self
    end
  end
end

Use by...

  def update
    render turbo_stream: stream_car.remove_css_class("#launch-card").set_value("#user_invite_form_name", value: "")
  end

Surprisingly, it works. Happy to make a PR and battle-test it more; just wanted to ask.