【问题标题】:Rails app and goliath api and database/models sharingRails 应用程序和 goliath api 以及数据库/模型共享
【发布时间】:2012-06-23 16:03:58
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby eventmachine goliath


    【解决方案1】:

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

    这是基于您的反馈的黑客攻击。

    【讨论】:

    • 顺便说一句:ActiveRecord gem 是'activerecord',要求如图所示。
    • 在您的示例中,您不与 rails 共享模型。此外,如果我们在模型中有很多逻辑,那么简单地要求它们是不安全的。需要同步逻辑去耦。另外如您所知,sqlite 没有异步驱动程序
    • 我已经编辑了示例来展示 Rails 模型的使用,不需要。 SQlite 的问题最好使用不同的数据库来解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    相关资源
    最近更新 更多