Skip to content

How to create a custom StructurePart

Clément Prod'homme edited this page Jun 16, 2019 · 4 revisions

As explained in the Readme page_parts are the building blocks of your view templates. Page parts are defined by it's partable_type which can be any of the following:

Spina::Line
Spina::Text
Spina::Image
Spina::ImageCollection
Spina::Color
Spina::Structure

If you don't find any of these partable types suitable, then it's very easy to add your own. In this guide we are going to create a very simple new partable_type for adding a score. Next we're going to combine this score with structure parts to create reviews

Model

Let's create the model first:

rails g model spina/score

Update the migration as below:

# /db/migrate/20160411143901_create_spina_scores.rb
class CreateSpinaScore < ActiveRecord::Migration
  def change
    create_table :spina_scores do |t|
      t.integer :score, :integer, null: false, default: 0

      t.timestamps null: false
    end
  end
end

Update the model:

# /app/models/spina/score.rb
module Spina
  class Score < ActiveRecord::Base
		
    has_many :page_parts, as: :page_partable
    has_many :layout_parts, as: :layout_partable
    has_many :structure_parts, as: :structure_partable

    validates :score, presence: true
    
    def content
      score
    end

  end
end
Views

Next we're going to add the views that will be used for the page forms:

# /app/views/spina/admin/structure_partables/scores/_form.html.haml
.horizontal-form-label
  = f.object.title
.horizontal-form-content
  = f.fields_for :structure_partable, f.object.structure_partable do |ff|
    .select-dropdown
      = ff.select :score, ((0..5))
Configuration

Next we're going to add our newly created partable_type to the configuration in our theme. First add the following to theme.structures

theme.structures = [{
    name: 'review',
    structure_parts: [{
      name:           'author',
      title:          'Author',
      partable_type:  'Spina::Line'
    }, {
      name:           'testimonial',
      title:          'Testimonial',
      partable_type:  'Spina::Text'
    }, {
      name:           'score',
      title:          'Score',
      partable_type:  'Spina::Score'        
    }]
  }]

Then add the structure to the theme.page_parts:

theme.page_parts = [{
    name:           'review',
    title:          'Review',
    partable_type:  'Spina::Structure'
  }]

Lastly add the page_part to a view_template:

theme.view_templates = [{
    name: 'show',
    title: 'Default',
    usage: 'Use for your content',
    page_parts: ['text', 'review']
  }]

After you restart the server and go to the page you'll see something like this:

Screenshot