Ruby BitBar 使用 Ruby 脚本,解决无法使用 Gem 的问题,以及读写文件路径存在空格的问题

chriszou · May 03, 2021 · Last by pynix replied at May 06, 2021 · 514 hits

BitBar(现改名为 xbar) 是一个开源的 Mac 小工具,它可以把任何东西放到 MacOS 的状态栏上面,我现在一般用它来做 TODO list。如下图所示

iShot2021-05-0317.36.38

不过,刚开始使用的时候,遇到这个一个问题,就是无法使用 gem,因为 BitBar 默认使用的 ruby 版本是系统版本,而我通常使用 rvm。翻了 BitBar 的 github issues 之后,找到这样一个解决办法

#!/usr/bin/env ruby

unless ENV['USING_RVM']
  # Re-run this script with RVM's default Ruby, after setting up the RVM path,
  # and setting USING_RVM to true, so that this sentry code won't run the second
  # time through.
  system(
    <<-EOF
      export USING_RVM=true
      export PATH="~/.rvm/bin:$PATH"
      rvm-auto-ruby #{File.expand_path(__FILE__)}
    EOF
  )
  # Return the exit code from running the script with RVM:
  exit $?.exitstatus.to_i
end

require 'faraday' # 可以正常使用Gem了
# 以下正常写你的脚本代码

不过,由于我的这个 script 文件是放在 iCloud 目录下的,具体路径是 /Users/myusername/Library/Mobile Documents/com~apple~CloudDocs/apps/BitBarPlugins,可以看到,中间有一个空格,于是,在代码运行到

rvm-auto-ruby #{File.expand_path(__FILE__)}

这一行的时候,遇到这样的错误提示:

Traceback (most recent call last):
ruby: No such file or directory -- /Users/myusername/Library/Mobile (LoadError)

解决办法是: require 'shellwords' 然后

rvm-auto-ruby #{File.expand_path(__FILE__)}

改成

rvm-auto-ruby #{File.expand_path(__FILE__.shellescape)} # __FILE__后面加了 .shellescape

这样,就解决了这个问题。

原文链接:https://chriszou.com/2021/05/03/bitbar-ruby-script-gem-shellwords/

不支持目录插件的话,使用 gem 还是挺坑的,散乱一堆文件。

You need to Sign in before reply, if you don't have an account, please Sign up first.