如何让 Rake 任务在我的 Sinantra 应用程序/环境下运行? [英] How do I make Rake tasks run under my Sinantra app/environment?

查看:25
本文介绍了如何让 Rake 任务在我的 Sinantra 应用程序/环境下运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的第一遍是这样的:

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

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:

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

但是我想不通的是如何设置环境以便rake任务可以在其下运行.任何帮助将不胜感激.

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.

推荐答案

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

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

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

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

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

require "rubygems"
require "bundler"
Bundler.setup

require 'sinatra'

将此设置放在单独的文件中可避免使您的 Rakefile 变得混乱,并且可用于通过 config.ru 启动您的 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:

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

run Sinatra::Application

这篇关于如何让 Rake 任务在我的 Sinantra 应用程序/环境下运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆