Sha256: d66f819dd8d5cf6fd43322e5c0f4ebebf1a01d1e6d18f7603ac21a62647f9ab1

Contents?: true

Size: 1.35 KB

Versions: 7

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

require "forwardable"

module Phlex::Rails
	# A decorator that buffers all missing method calls and captures the blocks passed to them.
	# @api private
	class Buffered < BasicObject
		extend ::Forwardable

		# @api private
		def self.define_builder_yielding_method(method_name, builder)
			class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
				# frozen_string_literal: true

				def #{method_name}(*args, **kwargs, &block)
					output = if block
						@object.#{method_name}(*args, **kwargs) { |builder|
							@view.capture do
								yield(
									::#{builder.name}.new(builder,
										view: @view
									)
								)
							end
						}
					else
						@object.#{method_name}(*args, **kwargs)
					end

					case output
					when ::ActiveSupport::SafeBuffer
						@view.instance_variable_get(:@_context).target << output
					end

					nil
				end
			RUBY
		end

		# @api private
		def initialize(object, view:)
			@object = object
			@view = view
		end

		def respond_to_missing?(...)
			@object.respond_to?(...)
		end

		def method_missing(*args, **kwargs, &block)
			output = if block
				@object.public_send(*args, **kwargs) { @view.capture(&block) }
			else
				@object.public_send(*args, **kwargs)
			end

			case output
			when ::ActiveSupport::SafeBuffer
				@view.instance_variable_get(:@_context).target << output
			end

			nil
		end
	end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
phlex-rails-1.2.2 lib/phlex/rails/buffered.rb
phlex-rails-1.2.1 lib/phlex/rails/buffered.rb
phlex-rails-1.2.0 lib/phlex/rails/buffered.rb
phlex-rails-1.1.2 lib/phlex/rails/buffered.rb
phlex-rails-1.1.1 lib/phlex/rails/buffered.rb
phlex-rails-1.1.0 lib/phlex/rails/buffered.rb
phlex-rails-1.0.0 lib/phlex/rails/buffered.rb