Last active
January 24, 2025 17:28
-
-
Save maxim/1e5c6816e97ecbe7e15eb3d364b0c9ea to your computer and use it in GitHub Desktop.
Page objects example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class WelcomePage | |
attr_reader :greeting, :recent_activity, :support_email | |
def self.from_user(user) | |
new \ | |
greeting: "Good #{user.time_of_day}, #{user.name}", | |
recent_activity: ActivityItem.from_user(user), | |
support_email: Rails.configuration.app.support_email | |
end | |
def initialize(greeting:, recent_activity:, support_email:) | |
@greeting = greeting | |
@recent_activity = recent_activity | |
@support_email = support_email | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def show | |
@page = WelcomePage.from_user(current_user) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2><%= @page.greeting %></h2> | |
<ul> | |
<%= @page.recent_activity.each do |item| %> | |
<li> | |
<strong><%= item.name %></strong>: <%= item.description %> | |
</li> | |
<% end %> | |
</ul> | |
<p>Get help: <%= mail_to @page.support_email %></p> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is an alternative example of welcome_page.rb using https://github.com/maxim/portrayal | |
# Assuming that ApplicationStruct has `extend Portrayal`. | |
# In this one I also do an example definition of ActivityItem class. | |
class WelcomePage < ApplicationStruct | |
def self.from_user(user) | |
new \ | |
greeting: "Good #{user.time_of_day}, #{user.name}", | |
recent_activity: ActivityItem.from_user(user), | |
support_email: Rails.configuration.app.support_email | |
end | |
keyword :greeting | |
keyword :support_email | |
keyword :recent_activity, defines: 'ActivityItem' do | |
def self.from_user(user) | |
user.events.last(3).map { |event| | |
new(name: event.name, description: event.description) | |
} | |
end | |
keyword :name | |
keyword :description | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment