bridgetownrb / bridgetown

A next-generation progressive site generator & fullstack framework, powered by Ruby
https://www.bridgetownrb.com
MIT License
1.16k stars 112 forks source link

Add the Resource equivalent to the `doc` method in builders #332

Closed jaredcwhite closed 3 years ago

jaredcwhite commented 3 years ago

Currently you can quickly spin up new Documents via a builder plugin using the doc method.

We need an equivalent resource method in builders with equivalent functionality, as the legacy content engine is deprecated and will be opt-in-only soon and eventually removed.

jaredcwhite commented 3 years ago

I don't have time to whip up an official PR for this quite yet, but I put this together specifically on a site project I'm working on for a client and it gets the job done. Leverages a ton of prior low-level work in the resource engine.

# add this to `site_builder.rb`:

require "bridgetown-core/utils/ruby_front_matter"

def resource(collection_name, path, &block)
  data = Bridgetown::Utils::RubyFrontMatter.new.tap { |fm| fm.instance_exec(&block) }.to_h
  if data[:content]
    data[:_content_] = data[:content]
    data.delete :content
  end

  Bridgetown::Model::Base.build(
    collection_name,
    path,
    data
  ).as_resource_in_collection
end

Here's how I'm using it in a builder plugin. Pulling data in from Prismic CMS…I'm quite impressed by the elegance of their Ruby API as you can see here.

class LoadStaff < SiteBuilder
  def build
    staff_bios = query_prismic :staff_bio
    with_links = link_resolver

    staff_bios.each do |bio|
      resource :staff_bios, "#{bio.slug}.html" do
        # Variable      # Prismic Field                 # Format
        date            bio.first_publication_date
        title           bio["staff_bio.name"]           .as_text
        category        bio["staff_bio.category"]       .as_text
        email_address   bio["staff_bio.email_address"]  .as_text
        phone_number    bio["staff_bio.phone_number"]   .as_text
        portrait_url    bio["staff_bio.portrait"]       .url
        content         bio["staff_bio.biography"]      .as_html with_links

        # Extra:
        parent_page_title   "Staff Directory"
        parent_page_link    "/staff"
        extra_page_class    "biography"
      end
    end
  end
end