ActionView Component

Justin Coyne

Stanford Libraries

Blacklight Summit - October 2019

Search Page

[4, 10] in /Users/jcoyne85/workspace/projectblacklight/blacklight/app/views/catalog/index.html.erb
    4: <% byebug %>
=>  5: <% unless has_search_parameters? %>
    6:   <%# if there are no input/search related params, display the "home" partial -%>
    7:   <%= render 'home' %>
    8:   <%= render 'shared/sitelinks_search_box' %>
    9: <% else %>
   10:   <%= render 'search_results' %>
(byebug) methods.count
715
https://github.com/github/actionview-component

What are ActionView Components?

Why should we use them?

Unit testable

Code coverage

Data flow

Better performance

# app/components/test_component.rb
class TestComponent < ActionView::Component::Base
  validates :content, :title, presence: true

  def initialize(title:)
    @title = title
  end

  private

  attr_reader :title
end
      
# app/components/test_component.html.erb
<span title="<%= title %>"><%= content %></span>
      
<%= render(TestComponent, title: "my title") do %>
  Hello, World!
<% end %>
      
require "action_view/component/test_helpers"

class MyComponentTest < Minitest::Test
  include ActionView::Component::TestHelpers

  def test_render_component
    assert_equal(
      '<span title="my title">Hello, World!</span>',
      render_inline(TestComponent, title: "my title") {
        "Hello, World!"
      }.css("span").to_html
    )
  end
end
      

In Blacklight?

Fin.

/