Documentation for creating custom Sprockets processors?

核能气质少年 提交于 2019-12-21 03:57:19

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/18128633/documentation-for-creating-custom-sprockets-processors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!