-
-
Save websebdev/b9a2fc018337acdb45faae04cec0ac47 to your computer and use it in GitHub Desktop.
Encapsulate complex view logic using models not connected to DB
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
<div class="<%= class_names(alert.classes) %>" role="alert"> | |
<% if alert.title %> | |
<h4 class="alert-heading"><%= alert.title %></h4> | |
<% end %> | |
<%= alert.description %> | |
<% if alert.dismissable %> | |
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> | |
<% end %> | |
</div> |
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 Alert | |
include ActiveModel::Model | |
attr_accessor :type, :dismissable, :title, :description | |
validates :type, inclusion: { in: %w(primary secondary success danger warning info light dark) } | |
validates :dismissable, inclusion: { in: [true, false] } | |
def initialize(type: "primary", dismissable: true, title: nil, description:) | |
@type, @dismissable, @title, @description = type, dismissable, title, description | |
end | |
def classes | |
["alert", "alert-#{type}", { "alert-dismissible": dismissable }] | |
end | |
def to_partial_path | |
validate! | |
"shared/alert" | |
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
<%= render Alert.new(title: "Test", description: "HOOOO") %> | |
or | |
<%= render Alert.new(type: "danger", description: flash[:alert])%> |
One thing I can't seem to figure out is how the class is assigned to the
alert
variable within the partial?
@prdanelli My guess is that Rails is calling something like record.class.to_s
on the instance or use the partial name to figure out the variable name. Could maybe even be record.model_name.name
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One thing I can't seem to figure out is how the class is assigned to the
alert
variable within the partial?