module Hokusai::Templatable
Templatable
models support taking a snapshot of their data, for later use stamping out clones.
Include this module to obtain the as_template
and from_template
methods that support a simple container such as Hokusai::Container
.
Configure it with the template
declaration, which accepts a list of columns and an includes
option for nested assocations.
Example¶ ↑
class Device < ActiveRecord::Base include Hokusai::Templatable has_many :interfaces template :name, :model, :location, :year, include: [:interfaces] end
Public Instance Methods
as_template()
click to toggle source
Serialize this object (and any included associations) according to the template specification.
# File lib/hokusai.rb, line 63 def as_template result_hash = {} 🌊[:columns].each_with_object(result_hash) do |column| result_hash[column] = read_attribute_for_template(column) end 🌊[:associations].each do |association| records = send(association) result_hash[association] = if records.respond_to?(:to_ary) records.to_ary.map { |r| r.as_template } else records.as_template end end result_hash end