Sha256: 7f6c947749a6d3843c4fa1f0f86f9c5c5e45687e6088775ae1e27da24c9328ea

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

module ViewComponentAttributes
  module WithContextAttributes
    ## Allows to configure default attributes for the component
    # specifically for the execution of a block. This comes handy
    # for passing defaults to sub-components without having
    # to have each component in the chain passing them down
    #
    # ```
    # - Component.with_attributes(option: 'value') do
    #   -# Say `GrandParendComponent` renders a `ParentComponent`
    #   -# Which in turn renders our `Component`
    #   -# Our component will have its `option` attribute defaulted
    #   -# to `'value'` when called without having `GrandParentComponent`
    #   -# or `ParentComponent` having to take responsibility for passing it
    #   = render GrandParentComponent.new(...)
    # ```

    extend ActiveSupport::Concern
    include ViewComponentAttributes::WithAttributes
    include MergeAttributes::Helper

    included do
      class_attribute :block_attributes

      # Prepend the initializer so its `super` calls
      # the class' `initialize` method rather than
      # the other way around
      prepend WithContextAttributes::Initializer
    end

    class_methods do
      def with_attributes(**attributes)
        self.block_attributes = attributes

        yield
      ensure
        self.block_attributes = nil
      end
    end

    module Initializer
      def initialize(*args, **initialize_attributes)
        super(*args, **merge_attributes(block_attributes || {}, initialize_attributes))
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
view_component_attributes-0.1.1 lib/view_component_attributes/with_context_attributes.rb