Difference between revisions of "Ruby on Rails"

From wiki.jasonsnotes.com
Jump to navigation Jump to search
(Created page with "== Ruby on Rails ==")
 
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
== Ruby on Rails ==
== View Components ==
(this is faster than partials, because it's plain ruby code)
 
bundle add view_component
 
rails g component header title
(creates)
/app/components/header_component.rb
/app/test/header_component_test.rb
/app/components/header_component.html.erb
 
/app/views/pages/home.html.erb:
 
<%= render(HeaderComponent.new("Hello World")) do %>
This content will be inserted into the Header Component!!
<% end %>
 
/app/components/header_component.rb:
 
Class HeaderComponent < ViewComponent::Base
  def initialize(title)
    @title = title
  end
end
 
/app/components/header_component.html.erb:
 
<h1><%= @title %></h1>
 
<p><%= content %></p>
 
/app/tests/header_component_test.rb
 
require "test_helper"
 
class HeaderComponentTest < ViewComponent::TestCase
 
  def test_renders_title
    expected = "TestTitle"
    render_inline HeaderComponent.new(expected)
    assert_text(expected)
  end
 
end
 
Test with `rails test`

Latest revision as of 16:31, 6 November 2025

View Components

(this is faster than partials, because it's plain ruby code)

bundle add view_component

rails g component header title (creates) /app/components/header_component.rb /app/test/header_component_test.rb /app/components/header_component.html.erb

/app/views/pages/home.html.erb:

<%= render(HeaderComponent.new("Hello World")) do %> This content will be inserted into the Header Component!! <% end %>

/app/components/header_component.rb:

Class HeaderComponent < ViewComponent::Base

 def initialize(title)
   @title = title
 end

end

/app/components/header_component.html.erb:

<%= @title %>

<%= content %>

/app/tests/header_component_test.rb

require "test_helper"

class HeaderComponentTest < ViewComponent::TestCase

 def test_renders_title
   expected = "TestTitle"
   render_inline HeaderComponent.new(expected)
   assert_text(expected)
 end

end

Test with `rails test`