0
votes

I wrote a generator plugin for my Jekyll site. It makes an API request to gather some necessary data to help with the build.

I'm using --livereload when running jekyll serve to develop locally. The generator seems to be called every time I save a file and regenerate the site. This uses up a lot of API requests made in my generator.

I only need to make that API request once. Is there a way for the generator to know how many times it gets called so that I can run it once and not on subsequent generations?

Here's the general impression of my generator plugin:

  class CloudinaryContent < Jekyll::Generator
    safe true

    def fetch(uri, env)
      # Make requests
    end

    # Fetch data before generating site
    def generate(site)
      require 'uri'
      require 'net/https'
      require 'json'

      # fetch data and store in global
      # variable for other plugins to use
      $site_data = fetch()
    end
  end

This is similar to Avoid repeated calls to an API in Jekyll Ruby plugin except I'm making API requests in a generator, and I only want to call the generator the first time jekyll serve is called, and not during subsequent reloads when files change during local development.

1

1 Answers

0
votes

I managed to achieve my goal, but not in an elegant manner. I added a counter variable called @render_count that starts at 1 and decrements every time the generator is called.

I added a condition to check if the counter is below 1, and immediately returns if the condition passes. Here's a sample:

def generate(site)
  if (!defined?@render_count)
    @render_count = 1
  end

  if @render_count < 1
    Jekyll.logger.info('already fetched data')
    return
  end

  # Perform business logic, set global variables
  ...

  Jekyll.logger.info('Data fetched successfully.')
  @render_count = @render_count - 1
end

I also tried making use of the :pre-render hook, but its behaviour is too similar to the Generator plugin since it gets called at every re-render.