How do I make Rake tasks run under my Sinantra app/environment?

喜你入骨 提交于 2019-12-18 12:27:34

问题


I'm using Sinatra, and I wanted to set up some of the convenience rake tasks that Rails has, specifically 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:

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.


回答1:


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

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'

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


来源:https://stackoverflow.com/questions/3692147/how-do-i-make-rake-tasks-run-under-my-sinantra-app-environment

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