Skip to content

Allow to define the view_context without rendering the component #1926

@mildred

Description

@mildred

Feature request

I'd like to be able to do something like:

comp = MyComponent.new().with_view_context(view_context)
comp.do_something_specific

That is, a way to associate the component with a view_context so I can do things like translations or access render-specific methods, but not perform the rendering step.

Motivation

I have a component that generates a HTML table. I want to make the table downloadable as a spreadsheet, but I'd like the table generation to happen within the component itself to keep all the things at the same place.

So in my rails controller, when I want to generate the spreadsheet, I create the component, then call the spreadsheet method on it that will generate the spreadsheet file. To do that I need translations, which requires the view_context.

Workaround

In my component I can define:

  def render?
    ! @skip_render
  end

  def with_no_render
    old = @skip_render
    @skip_render = true
    yield
    @skip_render = old
    self
  end

  def with_view_context(view_context)
    with_no_render do
      render_in(view_context)
    end
    self
  end

Then I can use my component like this:

    component = MyTableComponent.new(*args).with_view_context(view_context)
    add_table(spreadsheet, component.spreadsheet_table)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions