Skip to content

Instantly share code, notes, and snippets.

@websebdev
Last active August 10, 2021 12:18
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save websebdev/b9a2fc018337acdb45faae04cec0ac47 to your computer and use it in GitHub Desktop.
Save websebdev/b9a2fc018337acdb45faae04cec0ac47 to your computer and use it in GitHub Desktop.
Encapsulate complex view logic using models not connected to DB
<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>
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
<%= render Alert.new(title: "Test", description: "HOOOO") %>
or
<%= render Alert.new(type: "danger", description: flash[:alert])%>
@prdanelli
Copy link

One thing I can't seem to figure out is how the class is assigned to the alert variable within the partial?

@websebdev
Copy link
Author

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