这是在 Goliath 中使用 ActiveRecord 模型的快速技巧。使用这种方法,您可以在不使用 require 的情况下使用模型,但您没有模型级别的关系。为了获得 has_many 和 belongs_to 关系(在这种方法中),我将加载模型文件并在下面的类定义循环中包含包含此类单词的行。
require 'goliath'
require 'active_record'
require 'active_support'
# The location of the Rails app to integrate
RAILS_APP ||= ENV['HOME']+"/dev/qtrack"
# Load the ActiveRecord database configuration, development settings
configpath = File.join(RAILS_APP, "config", "database.yml")
config = YAML::load_file(configpath)
ActiveRecord::Base.establish_connection config["development"]
# Set the names of all Rails models to a constant
MODELS ||= []
models_dir = File.join(RAILS_APP, "app", "models")
model_names = Dir[models_dir+"/*.rb"]
# Loop over each file name, define a class for each
model_names.each do |fname|
mname = File.basename(fname, '.rb').titleize.sub(/ /, '')
eval %Q{
class ::#{mname} < ActiveRecord::Base
end
}
m = mname.constantize
MODELS << m unless MODELS.include?(m)
end
class Hello < Goliath::API
# default to JSON output, allow Yaml as secondary
use Goliath::Rack::Render, ['json', 'yaml']
def response(env)
# Create a Hash with each model name and the object count
models = MODELS.inject({}) {|hsh,model| hsh[model] = model.count; hsh }
[200, {}, models.to_json ]
end
end
这是基于您的反馈的 hack。