gpt4 book ai didi

ruby-on-rails - Rails 应用程序和 goliath api 以及数据库/模型共享

转载 作者:数据小太阳 更新时间:2023-10-29 06:44:29 26 4
gpt4 key购买 nike

我正在尝试使用 Goliath 框架创建异步 API。服务应该写入 mysql,将消息添加到 RabbitMQ 并接收返回的响应。还应该有一个用 Rails 构建的单独的管理应用程序。我对此有几个问题:

有没有办法在 Rails 和 Goliath 之间有效地共享模型?在 em 中使用 Activerecord 或任何其他 orm 有什么问题吗?是否有任何最佳实践、配置(连接池大小、驱动程序)或其他相关选项?我必须使用什么来接收来自 AMQP 的消息?构建一个单独的 eventmachine 守护进程会更好,还是我可以以某种方式使用 Goliath 的守护进程?感谢您的提前。

最佳答案

这是在 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

这是根据您的反馈进行的黑客攻击。

关于ruby-on-rails - Rails 应用程序和 goliath api 以及数据库/模型共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11137849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com