Sha256: e4b5b30ca8e6e6d713be7b616deba4bbb1b160991a991162c6d72c6eea7854c4

Contents?: true

Size: 1.32 KB

Versions: 5

Compression:

Stored size: 1.32 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.
	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(:@_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(:@_target) << output
			end

			nil
		end
	end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
phlex-rails-0.8.0 lib/phlex/rails/buffered.rb
phlex-rails-0.7.1 lib/phlex/rails/buffered.rb
phlex-rails-0.7.0 lib/phlex/rails/buffered.rb
phlex-rails-0.6.1 lib/phlex/rails/buffered.rb
phlex-rails-0.6.0 lib/phlex/rails/buffered.rb