Skip to content

Method Chaining #39

@rickychilcott

Description

@rickychilcott

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions