ruby 插件使用
Ruby developers are used to finding incredibly useful open source projects packaged as gems. In this tutorial, we’ll take a look at BitBar, an open source project that isn’t built in Ruby, but when combined with a small bit of Ruby can be incredibly powerful.
Ruby开发人员习惯于找到打包为gem的非常有用的开源项目。 在本教程中,我们将看一下BitBar,它不是一个用Ruby构建的开源项目,但是当与少量Ruby结合使用时,其功能将非常强大。
While the original project is no longer actively maintained, an updated fork of the project can be found here: https://github.com/kamenevn/bitbar
虽然不再积极维护原始项目,但是可以在这里找到项目的更新分支: https : //github.com/kamenevn/bitbar
BitBar provides Mac OS X users an easy way to create a menu bar item from the standard output of a script. I’ll show you how to create a simple site ping monitor, and then we’ll create a Twitter follower counter.
BitBar为Mac OS X用户提供了一种从脚本的标准输出创建菜单栏项的简便方法。 我将向您展示如何创建一个简单的站点ping监视器,然后我们将创建一个Twitter Follower计数器。
To install BitBar, visit the GitHub repository at https://github.com/kamenevn/bitbar. Download the zip file (the button to download is in the righthand sidebar). Inside the archived folder, you will find a “Releases” folder, which holds the BitBar.app file. Put this in your Applications directory. Opening this application launches BitBar.
要安装BitBar,请访问https://github.com/kamenevn/bitbar的GitHub存储库。 下载zip文件(要下载的按钮在右侧栏中)。 在存档文件夹内,您将找到一个“释放”文件夹,其中包含BitBar.app文件。 将其放在您的应用程序目录中。 打开此应用程序将启动BitBar。
BitBar is a simple application that runs all shell scripts in a given directory on an interval that is determined by the filename. Of course, you should be very careful when adding scripts to BitBar, especially if you are adding a low interval time.
BitBar是一个简单的应用程序,它以文件名确定的时间间隔运行给定目录中的所有shell脚本。 当然,将脚本添加到BitBar时应格外小心,尤其是在间隔时间较短的情况下。
To run a given file every 5 minutes, the naming structure would look something like this:
要每5分钟运行一个给定的文件,命名结构应如下所示:
my_script.5m.shOf course, you will also want to make your scripts executable. Note that BitBar refers to these scripts as “plugins” in their documentation.
当然,您还需要使脚本可执行。 请注意,BitBar在其文档中将这些脚本称为“插件”。
In order to add visible text to your BitBar plugin, you will need to send output to STDOUT. In Ruby, this is simply the output of puts. By default, BitBar will cycle through each line of the output, unless you output the specific string “—“; anything after this line will show up in a dropdown after you click the BitBar item in the menu bar.
为了向您的BitBar插件添加可见文本,您需要将输出发送到STDOUT 。 在Ruby中,这只是puts的输出。 默认情况下,除非您输出特定的字符串“ —”,否则BitBar将在输出的每一行之间循环。 单击菜单栏中的BitBar项目后,此行之后的所有内容都会显示在下拉列表中。
BitBar also allows changing the text color and responding to clicks. Clicks can either open a URL or trigger another shell script, and can be set to do so in the background.
BitBar还允许更改文本颜色并响应单击。 点击可以打开一个URL或触发另一个Shell脚本,并且可以设置为在后台这样做。
Here’s a simple Ruby script that would create a link to StackOverflow in BitBar:
这是一个简单的Ruby脚本,它将在BitBar中创建到StackOverflow的链接:
url = "https://stackoverflow.com" puts "Go to StackOverflow | href=#{url}"Notice the | separating the outputted text and the parameters for clicking. The href parameter tells BitBar to open this URL when clicked. Here’s a more complex example, showing some red text that triggers another executable script:
注意| 分离输出的文本和单击参数。 href参数告诉BitBar在单击时打开此URL。 这是一个更复杂的示例,显示一些红色文本触发另一个可执行脚本:
puts "Run My Script | color=#ff0000 bash=/path/to/your/script.sh"Of course, once again, you’ll want that script to be set to be executable using chmod.
当然,再次,您需要使用chmod将脚本设置为可执行的。
Finally, if the script takes parameters, you can add them using param1, param2, and param3. If you would like to execute the bash script in the background on click, set the parameter terminal= to false. For example, you might want to use the current time as a parameter for a script that runs in the background:
最后,如果脚本采用参数,则可以使用param1 , param2和param3添加参数。 如果您希望在单击时在后台执行bash脚本,请将参数terminal=设置为false 。 例如,您可能希望将当前时间用作在后台运行的脚本的参数:
current_time = Time.now.to_i puts "Run My Script | color=#ff0000 bash=/path/to/your/background_script.sh terminal=false param1=#{current_time}"Now that we know how BitBar works, let’s create a site monitor in Ruby that we can then use with BitBar. As a disclaimer, you should know that only checking a site’s status from your own computer may not give you the full picture. To really know if your sites are down, use monitoring services and sites like uptimerobot.com. But this little widget will provide a quick glance and signal potential problems as they occur.
现在我们知道BitBar的工作原理,让我们在Ruby中创建一个站点监视器,然后将其与BitBar一起使用。 作为免责声明,您应该知道,仅从您自己的计算机检查站点的状态可能无法提供完整的信息。 要真正知道您的站点是否关闭,请使用监视服务和uptimerobot.com等站点。 但是这个小部件可以快速浏览并在发生潜在问题时发出信号。
The required behavior is a bullet point that is red or green, depending on the status of a list of sites. I want to be able to keep that list of sites in an easy-to-update YAML file. When one of the sites goes down, I want to be able to click the bullet point in my menu bar and see the failing site. I also want to be able to click that menu item to visit the site in my browser.
所需的行为是红色或绿色的项目符号点,具体取决于站点列表的状态。 我希望能够将网站列表保留在易于更新的YAML文件中。 当其中一个站点出现故障时,我希望能够单击菜单栏中的项目符号点并查看出现故障的站点。 我还希望能够单击该菜单项以在浏览器中访问该站点。
Let’s get started with some Ruby!
让我们开始学习一些Ruby!
First, we’ll create a simple class called SiteChecker:
首先,我们将创建一个简单的类SiteChecker :
# /path/to/bitbar_plugins/site_checker/site_checker.rb require 'yaml' require 'net/http' class SiteChecker def initialize(sites) @sites = sites end def up?(server, port=80) http = Net::HTTP.start(server, port, {open_timeout: 5, read_timeout: 5}) response = http.head("/") response.code == "200" rescue Timeout::Error, SocketError false end def run results = {} @sites.map {|s| results[s] = up?(s) } results end endGreat! Now we have a simple Ruby class that can check any given site, can be initialized with a list of sites to check, and returns a hash of results.
大! 现在,我们有了一个简单的Ruby类,它可以检查任何给定的站点,可以使用要检查的站点列表进行初始化,并返回结果的哈希值。
Next, let’s write the actual BitBar plugin that will use the SiteChecker class. Add a folder to the BitBar plugins folder called site_checker and save the site_checker.rb file there. Next, create a file called site_checker.3m.sh, and place it in the BitBar plugins directory. Here’s what that file looks like:
接下来,让我们编写将使用SiteChecker类的实际BitBar插件。 在BitBar插件文件夹中添加一个名为site_checker文件夹,并将site_checker.rb文件保存在那里。 接下来,创建一个名为site_checker.3m.sh的文件,并将其放置在BitBar插件目录中。 该文件如下所示:
#!/usr/bin/env ruby # Note: the ruby path above should point to your Ruby installation. # You can verify this by checking `which ruby` $:.unshift File.dirname(__FILE__) require 'site_checker/site_checker.rb' require 'yaml' def run sites = YAML.load_file(File.join(__dir__, 'site_checker/sites.yml'))["sites"] site_checker = SiteChecker.new(sites) results = site_checker.run if results.values.include? false puts "• | color=#ff0000" puts "---" results.select {|key, val| val == false }.keys.each do |site| puts "#{site} down | href=http://#{site}" end else puts "• | color=#82B021" end end runThis simple script formats the output of our SiteChecker class for BitBar to use. Finally, we need to make sure we’ve added our sites.yml file inside our site_checker directory:
这个简单的脚本格式化了我们的SiteChecker类的输出,以供BitBar使用。 最后,我们需要确保已将site.yml文件添加到site_checker目录中:
sites: - "google.com" - "twitter.com" - "yoursite.com"Make sure your site uses only its domain name (without any protocols).
确保您的站点仅使用其域名(不包含任何协议)。
The final step is to make the script executable. You can do this by running chmod +x site_checker.3m.sh. The resulting file structure should look like this:
最后一步是使脚本可执行。 您可以通过运行chmod +x site_checker.3m.sh 。 生成的文件结构应如下所示:
├── site_checker │ ├── site_checker.rb │ └── sites.yml ├── site_checker.3m.shNext, let’s do something a bit more involved. We’ll show how many users we are following and how many users are following us on Twitter.
接下来,让我们做更多的事情。 我们将在Twitter上显示正在关注的用户数和正在关注我们的用户数。
The first step is to register an application with Twitter. Once you’ve followed the steps and successfully created your project, you will need to locate the API keys and access tokens for the application.
第一步是在Twitter上注册应用程序 。 完成这些步骤并成功创建项目后,您将需要找到该应用程序的API密钥和访问令牌。
Next, create a folder inside your BitBar plugins directory called twitter_counter, and an associated plugin file called twitter_counter.10m.sh.
接下来,创建您的BitBar plugins目录名为twitter_counter一个文件夹里面,和插件文件名为twitter_counter.10m.sh关联。
Inside of the newly created twitter_counter folder, create an account_detail.rb file. We will use this to create a simple class that will return follow count information for a Twitter account.
在新创建的twitter_counter文件夹内,创建一个account_detail.rb文件。 我们将使用它来创建一个简单的类,该类将返回Twitter帐户的关注计数信息。
The AccountDetail class looks like this:
AccountDetail类如下所示:
require 'twitter' class AccountDetail attr_accessor :user def initialize(username) @client = create_client @user = @client.user(username) end def followers user.followers_count end def followings user.friends_count end private def create_client Twitter::REST::Client.new do |config| config.consumer_key = "YOUR CONSUMER KEY" config.consumer_secret = "YOUR CONSUMER SECRET" config.access_token = "YOUR ACCESS TOKEN" config.access_token_secret = "YOUR ACCESS TOKEN SECRET" end end endMake sure you run gem install twitter if you have not already. In the previous example, we used built-in libraries. Twitter is a third-party gem that must be installed before this class will work.
如果尚未运行gem install twitter请确保尚未运行。 在前面的示例中,我们使用了内置库。 Twitter是第三方的gem,必须在该类正常工作之前安装它。
The AccountDetail class essentially wraps a very small subsection of the Twitter gem for our use case. Next, edit the twitter_counter.10m.sh file to look like this:
对于我们的用例, AccountDetail类本质上包装了Twitter gem的很小一部分。 接下来,编辑twitter_counter.10m.sh文件,如下所示:
#!/usr/bin/env $:.unshift File.dirname(__FILE__) require 'twitter_counter/account_detail' def run @account_detail = AccountDetail.new('your_twitter_name') puts "#{@account_detail.followers} followers" puts "#{@account_detail.followings} following" end runFinally, edit the permissions on the script to make it executable. As long as everything is set up correctly, you should see a simple widget in the menu that cycles between your “follower” count and your “following” count. Of course, we could use much more of the Twitter API to do even more interesting things!
最后,编辑脚本的权限以使其可执行。 只要一切设置正确,您都应该在菜单中看到一个简单的小部件,该小部件在“跟随者”计数和“跟随”计数之间循环。 当然,我们可以使用更多的Twitter API来做更多有趣的事情!
While this tool may not be used in a project you are intending to ship to your clients, it certainly can be a useful and fun tool to create your own native applications. Here are some ideas for more projects using BitBar:
尽管此工具可能不会在您打算交付给客户的项目中使用,但它无疑是创建自己的本机应用程序的有用且有趣的工具。 以下是使用BitBar进行更多项目的一些想法:
Build status indicator (integrating with something like CircleCI or Codeship) 构建状态指示器(与CircleCI或Codeship等集成) Stripe sales ticker 条纹销售行情 A simple easy-to-access action list for performing common scriptable tasks or macro-functions 一个简单易用的操作列表,用于执行常见的可编写脚本的任务或宏功能 Visual graphing of things with something like (Spark)[https://github.com/holman/spark] 用(Spark)之类的东西可视化绘图[https://github.com/holman/spark]Share your ideas with us here! Happy hacking!
在这里与我们分享您的想法! 骇客骇客!
翻译自: https://www.sitepoint.com/build-monitoring-widgets-ruby-bitbar/
ruby 插件使用