Skip to content

Instantly share code, notes, and snippets.

@hayesr
Created May 9, 2025 17:45
Show Gist options
  • Save hayesr/d73b7848b7926ffe8c8bbbf59991da9f to your computer and use it in GitHub Desktop.
Save hayesr/d73b7848b7926ffe8c8bbbf59991da9f to your computer and use it in GitHub Desktop.

Revisions

  1. hayesr created this gist May 9, 2025.
    41 changes: 41 additions & 0 deletions component_presenter.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    # Your component classes can inherit from this
    class ComponentPresenter
    # A 'macro' to define the partial path at the top of the class like:
    # partial_path: 'components/popover'
    # Or just define your own partial_path method
    #
    def self.partial_path(path)
    define_method(:partial_path) do
    path
    end
    end

    attr_reader :template

    # What rails will call when you have something like
    # <%= render(MyComponent.new(args)) %>
    # in a view.
    #
    # This sets template which you can use to call Rails view helpers or your
    # own helpers, like `template.content_tag`.
    def render_in(template, *_args, &_block)
    @template = template

    if render?
    template.render(partial: partial_path, locals: locals)
    else
    ""
    end
    end

    # Overwrite in children to control rendering
    # This is borrowed straight from ViewComponent
    def render?
    true
    end

    # Passed to the partial
    def locals
    {}
    end
    end