Documentation for creating custom Sprockets processors?
Asked Answered
L

1

11

I'm trying to create a sprockets preprocessor for Rails that finds .png.rb files in the asset pipeline and uses them to generate png screenshots of various pages in my application.

I've read up on this topic quite a bit but I can't seem to find any straightforward documentation on how to get this set up. Help, please?

Here's what I have so far:


/initializers/sprockets.rb:

require 'screenshot_preprocessor'

Rails.application.assets.register_mime_type('screenshot/png', '.png.rb')
Rails.application.assets.register_preprocessor('screenshot/png', ScreenshotPreprocessor)

/lib/screenshot_preprocessor.rb:

class ScreenshotPreprocessor
  # What API do I need to provide here?
  #   - What methods do I need to provide?
  #   - What parameters does Sprockets pass me?
  #   - What do I need to return to Sprockets?
end
Loera answered 8/8, 2013 at 14:26 Comment(1)
Note: I've also opened an issue about this on GitHub.Loera
L
7

Okay, I'm still not sure where to find documentation on this. But, by reading Sprockets' source code, playing around with the pry debugger, and reading blog posts from people who have done similar things with Sprockets, I was able to come up with this:


/initializers/sprockets.rb:

require 'screenshot_generator'

Rails.application.assets.register_engine('.screenshot', ScreenshotGenerator)

/lib/screenshot_generator.rb:

require_relative 'capybara_screenshot' # Don't worry about this, it's not
                                       # relevant to this question.

class ScreenshotGenerator < Sprockets::Processor
  def evaluate(context, locals)
    generator_class = ScreenshotGenerator.get_generator_class(context.pathname)

    return generator_class.new.generate
  end

  private

  def self.get_generator_class(generator_file)
    # This evaluates the Ruby code in the given file and returns a class that
    # can generate a binary string containing an image file.
    # (Code omitted for brevity)
  end
end

This works fine for me now, but I'd really prefer to see some real documentation on how Sprockets preprocessors, postprocessors, and engines work. If anyone finds any such documentation, please post an answer.

Loera answered 9/8, 2013 at 15:51 Comment(1)
I know that this is an old question/answer, but since I am currently working on a Sprockets Postprocessor, I used the guide on extending Sprockets as a starting point.Jody

© 2022 - 2024 — McMap. All rights reserved.