【问题标题】:Force .rb file running under specific ruby versions强制 .rb 文件在特定 ruby​​ 版本下运行
【发布时间】:2020-07-20 08:05:28
【问题描述】:

我在.rb 文件中编写了一个ruby 脚本。它使用最新的 Ruby 特性(2.7 版)。有没有办法强制这个.rb 文件只能在特定的Ruby 版本范围内执行?例如,.rb 文件的第一行可能是:

#! ruby 2.7+
# This .rb file can only be run with Ruby version 2.7 or above

【问题讨论】:

  • 如果你有一个使用ruby 指令的Gemfile,你可以这样做。

标签: ruby version


【解决方案1】:

使用 gem semantic 来处理当前 Ruby 版本的解析:

require 'semantic'

# Require >= 2.7 < 3
exit unless Semantic::Version.new(RUBY_VERSION).satisfies?('~> 2.7')

# Require >= 2.7, including 3 and above
exit unless Semantic::Version.new(RUBY_VERSION).satisfies?('>= 2.7')

这需要您在应用中使用捆绑器和 Gemfile。

其他比较器列在the source code for the gem

if ['<', '>', '<=', '>='].include?(comparator)
  satisfies_comparator? comparator, pad_version_string(other_version_string)
elsif comparator == '~>'
  pessimistic_match? other_version_string
else
  tilde_matches? other_version_string
end

这将允许您微调您的版本要求。

【讨论】:

    【解决方案2】:

    天真,

    unless RUBY_VERSION[0, 3] == "2.7"
      puts "You need 2.7")
      exit
    end 
    

    【讨论】:

    • 小心,因为这可能会检测到2.2.7。考虑:start_with?('2.7')
    • 好的,谢谢,我忽略了这一点并编辑了我的答案。不幸的是,start_with 是 ActiveSupport 方法中的一种。
    • Ruby,而不是 Rails,有 String#start_with,参见:ruby-doc.org/core-2.7.0/String.html#method-i-start_with-3F
    • 但如果他们不在 2.7 上,这将返回 NoMethodError;从这个意义上说,他们可以从中解救出来:)
    • 是什么让您认为start_with 仅在 2.7 中可用?我在1.8.7 之前停止检查。此外,您的答案有语法错误。 (未打开的括号,Rubyist 通常不会在调用puts 时使用)
    猜你喜欢
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    相关资源
    最近更新 更多