Rails使用Grunt或Gulp

时间:2015-05-18 03:43:23

标签: ruby-on-rails gruntjs gulp sidekiq

My Rails 4应用程序允许其用户导入一些Adobe Edge动画文件(广告)。虽然它有效,但Adobe Edge正在加载一堆文件,这些文件可以使用像Grunt或Gulp这样的工具进行缩小和优化(图像)。

我使用CarrierWave上传文件,然后如果它们在存档中,我会将它们解压缩:

class FileUploader < CarrierWave::Uploader::Base
  after :store, :uncompress_and_update_reference

  def uncompress_and_update_reference(_file)
    return unless archive_is_supported?(model.ext)
    extractor = Uploader::Archive.const_get("Extractor#{model.ext.upcase}").new
    Uploader::Archive::PubArchive.new(extractor, model, full_path).extract_and_save
  end
end

我在想我可以在后台工作中使用Grunt或Gulp(例如使用Sidekiq)来处理我需要的那些提取文件。问题是我该怎么做?

从我读过的内容来看,为了运行gruntgulp,他们都需要分别拥有Gruntfile.jsGulpfile.js,因为我需要在提取的文件夹中动态运行它,所以很棘手。

任何?

1 个答案:

答案 0 :(得分:1)

好的,我终于创建了一个Node CLI来处理这种情况。由于我需要能够在文件夹内动态优化文件,因此使用命令行实用程序是最佳方案:

<强> cli.js

#!/usr/bin/env node

'use strict';

var meow      = require('meow');
var fs        = require('fs');
var optimizer = require('./');

var cli = meow({
  help: [
    'Usage : pub-optimizer <path_to_optimize> <path_to_optimize>',
    ''
  ].join('\n')
});

var paths = cli.input

paths.forEach(function (path) {
  if (fs.existsSync(path) {
    optimizer.minify(path);
  } else {
    console.log(path + ' is not a valid directory.')
  }
});

<强> index.js

'use strict';

var gulp     = require('gulp');
var imagemin = require('gulp-imagemin');
var pngquant = require('imagemin-pngquant');

exports.minify = function (folderPath) {

  // Remove trailing slash
  folderPath = folderPath.replace(/\/+$/, "");

  // Optimize images
  gulp.task('default', function () {
    return gulp
      .src(folderPath + '/**/*.{png,jpg,jpeg,gif,webp,svg}')
      .pipe(imagemin({
        progressive: true,
        use: [pngquant()]
      }))
      .pipe(gulp.dest(folderPath));
  });

  gulp.start();
};

然后我需要做的就是从我的Rails应用程序调用CLI:

<强>上传/ file_uploader.rb

class FileUploader < CarrierWave::Uploader::Base
  after :store, :uncompress_and_update_reference

  def uncompress_and_update_reference(_file)
    return unless archive_is_supported?(model.ext)
    extractor = Uploader::Archive.const_get("Extractor#{model.ext.upcase}").new
    Uploader::Archive::PubArchive.new(extractor, model, full_path).extract_and_save

    PubOptimizerWorker.perform_async(fullpath)
  end
end

<强>工人/ pub_optimizer_worker.rb

class PubApprovalRequestWorker
  include Sidekiq::Worker
  sidekiq_options queue: :pub

  def perform(path)
    system("pub-optimizer #{path}")
  end
end

希望这可能有助于某人。