Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Documentation for creating custom Sprockets processors?

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
like image 943
Ajedi32 Avatar asked Aug 08 '13 14:08

Ajedi32


1 Answers

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.

like image 121
Ajedi32 Avatar answered Nov 07 '22 00:11

Ajedi32