Saturday, June 13, 2020

Pantheios.Ruby Tutorial, part 2: First Program

This is the second part in a series of tutorial posts illustrating how to use Pantheios.Ruby. The first part is here.

Project Setup

In this part we're going to do some basic project setup. Expert Rubyists may wish to skip to the next section.

First step is to create a git project. Create a new directory and do a Git init:

$ git init

I'm going to use Bundler, so next do a Bundle init:

$ bundle init

I happen to know that we'll be using recls.Ruby as well as Pantheios.Ruby, so let's edit the generated bundle file to look something like the following:

  # frozen_string_literal: true
  
  source "https://rubygems.org"
  
  git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
  
  gem "pantheios-ruby"  
  gem "recls-ruby"  

Then just bundle it:

$ bundle

All being well, add Gemfile and the newly generated Gemfile.lock into git and commit.

First Program

Ok, now on to the first program. First create the script searcher.rb and require and include both libraries, as follows:

  1 #! /usr/bin/env ruby
  2 
  3 require "pantheios"
  4 require "recls"
  5 
  6 include ::Pantheios
  7 

Give it a run to verify Bundler did its job ok.

$ ruby searcher.rb

Go ahead and commit that, then we'll make it a little interesting by doing a search and logging some output.

  1 #! /usr/bin/env ruby
  2 
  3 require "pantheios"
  4 require "recls"
  5 
  6 include ::Pantheios
  7 
  8 Recls.file_rsearch(nil, nil).each do |fe|
  9 
 10     log(:informational, "found '#{fe.search_relative_path}'")
 11 end 
 12    

This uses the Recls module function file_rsearch() to conduct a recursive search for files, returning an Enumerable object on which we call each passing the block that uses Pantheios.Ruby's log() method to record each item found. On my machine it produces the following output

[searcher, 70123163703220, 2020-06-14 09:31:35.142106, Informational]: found 'searcher.rb'
[searcher, 70123163703220, 2020-06-14 09:31:35.142559, Informational]: found 'Gemfile'
[searcher, 70123163703220, 2020-06-14 09:31:35.143248, Informational]: found 'Gemfile.lock'

In the next instalment we'll examine the aspects of this program and its output and make some customisations to what gets logged and in what form.


No comments:

Post a Comment