Class: PandaCms::Template
- Inherits:
-
ApplicationRecord
- Object
- ActiveRecord::Base
- ApplicationRecord
- PandaCms::Template
- Defined in:
- app/models/panda_cms/template.rb
Overview
Represents a template in the Panda CMS application.
Class Method Summary collapse
- .default ⇒ Object
-
.generate_missing_blocks ⇒ void
Generate missing blocks for all templates.
Class Method Details
.default ⇒ Object
29 30 31 |
# File 'app/models/panda_cms/template.rb', line 29 def self.default find_by(file_path: "layouts/page") || first end |
.generate_missing_blocks ⇒ void
This method returns an undefined value.
Generate missing blocks for all templates
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'app/models/panda_cms/template.rb', line 35 def self.generate_missing_blocks # Loop through all templates in app/views/layouts/*.html.erb Dir.glob("app/views/layouts/*.html.erb").each do |file| # TODO: Delete all blocks which aren't in use by a template? File.open(file).each_line do |line| # Matches: # PandaCms::RichTextComponent.new(key: :value) # PandaCms::RichTextComponent.new key: :value, key: value line.match(/PandaCms::([a-zA-Z]+)Component\.new[ \(]+([^\)]+)[\)]*/) do |match| # Extract the hash values template_path = file.gsub("app/views/", "").gsub(".html.erb", "") template_name = template_path.gsub("layouts/", "").titleize # Create the template if it doesn't exist template = PandaCms::Template.find_or_create_by!(file_path: template_path) do |template| template.name = template_name end next if match[1] == "PageMenu" # Skip PageMenu blocks next if match[1] == "Menu" # Skip Menu blocks # Previously used match[1].underscore but this supports more complex database # operations, and is more secure as it'll force the usage of a class block_kind = "PandaCms::#{match[1]}Component".constantize::KIND match[2].split(",").map do |keyvar| key, value = keyvar.split(":", 2) next if key != "key" block_name = value.to_s.strip.tr(":", "") # Create the block if it doesn't exist # TODO: +/- the output if it's created or removed begin block = PandaCms::Block.find_or_create_by!(template: template, kind: block_kind, key: block_name) do |block| block.name = block_name.titleize end rescue ActiveRecord::RecordInvalid => e raise "Error creating block '#{block_name}' on template '#{template_name}': #{e.}" end # For the given block, create the block_content for each page using the template template.pages.each do |page| PandaCms::BlockContent.find_or_create_by!(block: block, page: page) do |block_content| block_content.content = "" end end end end end end end |