SelfRenderer
Rails model & object rendering outside the context of web requests.
Use Cases
- Serialize model in background job to send over ActionCable
- etc....
Quick Start
# Gemfile
gem "self_renderer"
# app/models/user.rb
class User < ApplicationRecord
include SelfRenderer
end
<!-- app/views/users/show.html.erb -->
<h1>User</h1>
<%= render "item" %>
<!-- app/views/users/_item.html.erb -->
<p><%= @user.name %></p>
# app/views/users/show.json.jbuilder
json.partial! "item"
# app/views/users/_item.json.jbuilder
json.name @user.name
# render html strings
User.find(1).render_with(template: "users/show.html")
User.find(2).render_with(partial: "users/item.html")
# render json strings
User.find(3).render_with(template: "users/show.json")
User.find(4).render_with(partial: "users/item.json")
# render ruby hashes
User.find(5).render_to_hash(template: "users/show.json")
User.find(6).render_to_hash(partial: "users/item.json")