Sha256: efe929e702fe96b8fedb51ec9cc8cceffe85ade55833b956f2ddb165cf4f20a7

Contents?: true

Size: 1.12 KB

Versions: 22

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

# # PageBuilder
#
# PageBuilder is a simple DSL for building pages, for use in ie. seeds.rb
#
# Example:
#
#   PageBuilder.build(User.first) do
#     page "Home", template: "home"
#     page "Products" do
#       page "Product 1"
#       page "Product 2"
#     end
#     page "Contact", unique_name: "contact"
#   end
class PageBuilder
  attr_reader :user, :locale, :parent

  class << self
    def build(user, locale: nil, parent: nil, &block)
      new(user, locale: locale, parent: parent)
        .run(&block)
    end
  end

  def initialize(user, locale: nil, parent: nil)
    @user = user
    @locale = locale || I18n.default_locale
    @parent = parent
  end

  def page(name, options = {}, &block)
    page = Page.create(
      { name: name }.merge(default_options).merge(options)
    )
    if block_given?
      self.class
          .new(user, locale: locale, parent: page)
          .run(&block)
    end
    page
  end

  def run(&block)
    instance_eval(&block)
  end

  private

  def default_options
    {
      author: user,
      parent: parent,
      status: 2,
      locale: locale
    }
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
pages_core-3.8.0 app/models/page_builder.rb
pages_core-3.7.0 app/models/page_builder.rb