首页 文章

gemspec中的条件ruby gem依赖项

提问于
浏览
7

我正在构建一个在迁移中使用外键的rails引擎 .

add_foreign_key "theblog_content_nodes",
                    "theblog_content_statuses", column: :content_status_id

从版本 4.2 rails本身支持外键,但在我们使用 foreigner gem之前 . 如果我们尝试使用 foreignerrails 4.2 和更新,我们会收到错误 .

所以,因为我要从4.0.1开始支持rails,所以我必须在我的gemspec中使用条件依赖 .

我找到了可能的解决方案here但我不知道如何检查gemspec中的rails版本 .

# sidekiq-spy.gemspec

if RUBY_VERSION >= '2.1'
  spec.add_development_dependency "curses", "~> 1.0"
end

NOTE:

我有另一个临时解决方案:我只是检查迁移中的 Foreigner 可用性 . 如果它不可用我只是不创建外键:

if defined?(Foreigner)
  add_foreign_key "theblog_content_nodes",
                  "theblog_content_statuses", column: :content_status_id
end

但我想为旧的rails版本添加 foreigner 依赖项 .

1 回答

  • 2

    要访问rails版本,我们可以使用类似下面的内容(基于this answer):

    require 'rubygems'
    
    rails_gem = Gem::Specification.select {|z| z.name == "rails"}.max_by {|a| a.version}
    p rails_gem.version.version
    #=> "4.2.5"
    

相关问题