如何在我的Sinantra应用程序/环境下运行Rake任务?

时间:2022-06-10 19:16:36

I'm using Sinatra, and I wanted to set up some of the convenience rake tasks that Rails has, specifically rake db:seed.

我正在使用Sinatra,我想设置一些Rails具有的便利rake任务,特别是rake db:seed。

My first pass was this:

我的第一关是这样的:

namespace :db do
  desc 'Load the seed data from db/seeds.rb'
  task :seed do
    seed_file = File.join(File.dirname(__FILE__), 'db', 'seeds.rb')
    system("racksh < #{seed_file}")
  end
end

racksh is a gem that mimics Rails' console. So I was just feeding the code in the seed file directly into it. It works, but it's obviously not ideal. What I'd like to do is create an environment task that allows commands to be run under the Sinanta app/environment, like so:

racksh是一个模仿Rails控制台的宝石。所以我只是将种子文件中的代码直接输入其中。它有效,但显然不理想。我想做的是创建一个环境任务,允许命令在Sinanta应用程序/环境下运行,如下所示:

task :environment do
  # what goes here?
end

task :seed => :environment do
  seed_file = File.join(File.dirname(__FILE__), 'db', 'seeds.rb')
  load(seed_file) if File.exist?(seed_file)
end

But what I can't figure out is how to set up the environment so the rake tasks can run under it. Any help would be much appreciated.

但我无法弄清楚如何设置环境以便rake任务可以在其下运行。任何帮助将非常感激。

1 个解决方案

#1


10  

I've set up a Rakefile for Sinatra using a kind of Rails-like environment:

我使用一种类似Rails的环境为Sinatra设置了一个Rakefile:

task :environment do
  require File.expand_path(File.join(*%w[ config environment ]), File.dirname(__FILE__))
end

You then have something in config/environment.rb that contains what you need to start up your app properly. It might be something like:

然后,您在config / environment.rb中有一些内容,其中包含正确启动应用程序所需的内容。它可能是这样的:

require "rubygems"
require "bundler"
Bundler.setup

require 'sinatra'

Putting this set-up in a separate file avoids cluttering your Rakefile and can be used to launch your Sinatra app through config.ru if you use that:

将此设置放在一个单独的文件中可以避免混乱您的Rakefile,如果您使用它,可以通过config.ru用于启动Sinatra应用程序:

require File.expand_path(File.join(*%w[ config environment ]), File.dirname(__FILE__))

run Sinatra::Application

#1


10  

I've set up a Rakefile for Sinatra using a kind of Rails-like environment:

我使用一种类似Rails的环境为Sinatra设置了一个Rakefile:

task :environment do
  require File.expand_path(File.join(*%w[ config environment ]), File.dirname(__FILE__))
end

You then have something in config/environment.rb that contains what you need to start up your app properly. It might be something like:

然后,您在config / environment.rb中有一些内容,其中包含正确启动应用程序所需的内容。它可能是这样的:

require "rubygems"
require "bundler"
Bundler.setup

require 'sinatra'

Putting this set-up in a separate file avoids cluttering your Rakefile and can be used to launch your Sinatra app through config.ru if you use that:

将此设置放在一个单独的文件中可以避免混乱您的Rakefile,如果您使用它,可以通过config.ru用于启动Sinatra应用程序:

require File.expand_path(File.join(*%w[ config environment ]), File.dirname(__FILE__))

run Sinatra::Application