在一些教程的帮助下,我创建了我的第一个简单的gem,它将Sass / CSS文件添加到应用程序的assets / stylesheets目录中。
这很尴尬,但问题是我不知道如何在应用程序中运行我的宝石。
gemspec:
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'example/version'
Gem::Specification.new do |spec|
spec.name = "Example"
spec.version = Example::VERSION
spec.authors = ["***"]
spec.email = ["***"]
spec.description = %q{Provide CSS styles}
spec.summary = %q{Provide CSS styles}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "redcarpet", "~> 1.17"
spec.add_development_dependency "yard", "~> 0.7.5"
end
example.rb:
require "example/version"
module Example
def self.install
original_dir = Dir["/lib/example/*.css.scss"]
original_dir.each do |f|
name = File.basename('main', '.css.scss')
destination_dir = "/app/assets/stylesheets/#{name}"
FileUtils.cp(main, destination_folder)
end
end
end
Rake文件:
require "bundler/gem_tasks"
require 'yard'
YARD::Rake::YardocTask.new
我相信我应该写一些rake任务,但我不确定我该怎么做。
谢谢!
答案 0 :(得分:1)
我学会了如何解决我的问题。从gem文件运行ruby代码的最佳方法是将其移动到rails生成器。例如,创建包含代码的文件lib/generators/initializer_generator.rb
(我举了一个例子):
class InitializerGenerator < Rails::Generators::Base
def create_initializer_file
create_file "config/initializers/initializer.rb", "# Add initialization content here"
end
end
然后将您的gem添加到Gemfile,安装它并运行rails g initializer