7

I'm building a rails engine which uses foreign keys in migrations.

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

From the version 4.2 rails supports foreign keys by itself but before we used foreigner gem for this. If we try to use foreigner with rails 4.2 and newer we get an error.

So since I'm going to support rails starting from 4.0.1 I have to use conditional dependency in my gemspec.

I found possible solution here but I have no idea how to check rails version in the gemspec.

# sidekiq-spy.gemspec

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

NOTE:

I have another temporary solution: I just check Foreigner availability in my migrations. If it is unavailable I just don't create foreign keys:

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

But I'd like to add foreigner dependency for old rails versions.

Nickolay Kondratenko
  • 1,871
  • 2
  • 21
  • 25
  • Did you think of providing two different versions of your gem for that scenarios? – iltempo Dec 02 '15 at 13:26
  • @iltempo, I can even use the one version for both scenarios. Just add note that we have to add `gem "foreigner"` to `Gemfile` if Rails version is less than `4.2` and we want to use foreign keys. – Nickolay Kondratenko Dec 02 '15 at 13:54

1 Answers1

2

To access rails version, we can use something like below (based on 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"
Community
  • 1
  • 1
Wand Maker
  • 18,476
  • 8
  • 53
  • 87
  • Unfortunately it seems we have no access to `Rails` inside the gemspec. I've just got the following error: `uninitialized constant Rails from /Users/kont/projects/theblog/theblog.gemspec:21:in 'block in
    '`
    – Nickolay Kondratenko Dec 02 '15 at 12:51
  • Updated the answer to use `rubygems` API. Please check whether this will work for you – Wand Maker Dec 02 '15 at 13:10
  • I tried this in both engine itself and in the app using this engine. It seems to work properly. Thanks! – Nickolay Kondratenko Dec 02 '15 at 14:06
  • 1
    Recently The CI failed with the following error: `There was a NoMethodError while loading theblog.gemspec: undefined method `version' for nil:NilClass from /Users/kont/projects/drevo/theblog/theblog.gemspec:26:in `block in
    '` I found that `Gem::Specification` does not contain `Rails` yet
    – Nickolay Kondratenko Jan 26 '16 at 09:54