Plough => Ruby

Journey through ruby

Ruby Command Line Flag for Debugging

Reading open source code is almost always a good idea. Open source code has the benefit of being reviewed by a lot of committed users and it just shows the good patterns of programming. For instance, I once looked at Arel, and the code demonstrates an exemplary use of visitor pattern. There isn’t much code there, yet it manages to achieve so much.

Recently, I was reading some open source code recently and spotted $DEBUG environment variable in quite a few places. At the time, I thought it must be something the author used to simplify debugging. But, no, it’s defined and used by ruby core. Ruby provides a debug flag (-d or –debug) which when used would set the $DEBUG to true.

Try running the following script in irb, pry or whatever else you use:

1
ruby -d -e 'if $DEBUG; puts "Debugging"; end'

and you should see something like this as output:

1
2
3
4
5
RUBY_GC_HEAP_FREE_SLOTS=200000 (default value: 4096)
RUBY_GC_MALLOC_LIMIT=90000000 (default value: 16777216)
Exception `LoadError' at /Users/andhapp/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/rubygems.rb:1222 - cannot load such file -- rubygems/defaults/operating_system
Exception `LoadError' at /Users/andhapp/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/rubygems.rb:1231 - cannot load such file -- rubygems/defaults/ruby
Debugging

Don’t worry about the two exceptions as in debug mode exceptions are displayed even when they are rescued.

Setting Up Chrome Selenium Driver for Capybara When Using Chrome Canary on a Mac

We have been adding Rspec + Capybara to Suggestion.io to ensure we don’t create any regression bugs. There are plenty of resources online to set-up Capybara to use Selenium’s Chrome driver (instead of Firefox).

But, what if you are using Chrome Canary as your browser?

You would probably see the following error:

Selenium::WebDriver::Error::UnknownError: unknown error: cannot find Chrome binary

There are two ways to fix this issue:

 Solution 1 - Download Chrome

Whilst, searching for the solution, I ended up on ChromeDriver’s wiki. It clearly states that Chrome driver expects the Chrome binary to be in:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome

That’s exactly where Chrome is installed on a Mac, so, to fix this issue just download Chrome.

Solution 2 - Pass the location of Chrome Canary’s binary to Selenium Chrome Driver via Capybara

Downloading Chrome just for the sake of passing specs doesn’t make sense. Googling revealed that there’s something called ‘ChromeOptions’, but, how the hell do I pass that option from Capybara, so that it get’s passed correctly to Selenium Chrome driver. After, trawling through the capybara and selenium-webdriver source, I found a way to pass the location of Chrome Canary as the binary. Here’s how:

Capybara.register_driver :chrome do |app|
  Capybara::Selenium::Driver.new(app, 
    browser: :chrome, 
    desired_capabilities: {
      "chromeOptions" => {
        "binary" => '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary' 
      } 
    })
end

The ‘binary’ option specifies the location of Chrome Canary’s binary on your Mac.

That was a couple of hours well spent. Hope it helps!

An Unsual Thing About kanji(Japanese)

Recently, I was reading an article on natural language processing of Japanese characters and came across something very unusual about the way Japanese characters are written, there is no delimiters between the words, for example, if ‘Ruby’ and ‘Blog’ are two kanji characters then they will be written as ‘RubyBlog’ with no delimiter (space in English) between them. It makes segmenting Japanese text a lot harder since combination of characters could mean two entirely different things.

I just found it very fascinating and challenging at the same time.

RSpec Verifying Doubles

RSpec 3 has been full of some good stuff and I have full admiration for the people behind it. Even the upgrade process was well thought out keeping in mind the end users. As developers, we are used to handle poor upgrade process pretty well, but RSpec totally changed my opinion.

Whilst merging pull request for TextRazor, I decided to upgrade the gem to RSpec3. I was meant to do that for sometime anyways, and the pull request opened up the perfect opportunity for it. I stumbled upon a very interesting new feature in RSpec3, called verifying doubles. This functionality makes rspec-fire totally obsolete. It verifies that any methods being stubbed would be present on the instance of the class being stubbed and also the number of argument the method accepts. This is pretty cool. I always used rspec-fire to make sure that my stubbed method existed on the class. In the light of these updates, I removed rspec-fire as a dependency from TextRazor. Makes it even more lightweight.

Thanks again to RSpec team!

Ruby Puts Command

Ruby’s puts command will lead the ‘most used command’ competition in the language. It’s probably the first command you run when you fire up irb, or write HelloWorld.rb. I have been using it from day 1, for debugging, printing out the progress of long running scripts and so on. I recently found couple of nifty things you can do with puts command:

  • You can pass it multiple arguments and it will print them on the screen with a line break, for example:
irb(main):001:0> puts "First", "day"
First
day
=> nil
  • Secondly, you can pass it an array of elements, and it will print the elements with a line break, for example:
irb(main):004:0> puts ["Second", "Day"]
Second
Day
=> nil

Hope you can use this to replace multiple calls to puts in your code.

You Want to Be a Programmer?

But, you have no time

No one has time!

The rise of billion dollar startups that get acquired in 6 months (or longer, perhaps) from launch gives a false impression that programming is easy, and hence shouldn’t take very long to learn. After all, you have a billion dollar idea you would like to start working on.

Let’s conduct a small study. Why don’t you spend an hour on StackOverflow? Why? To observe how users, without doing any research, ask the same questions over and over and over again. They just want to learn how this works, not why this works and not something else. I’m possibly guilty of the same mistakes, and I have been trying to amend them ever since.

You need this

As a result of these observations, and experience in teaching, I’ve come up up with a list of few qualities that can make you a better programmer:

  • Learner - Learning never stops for a programmer and that’s the fun of it. You will have to spend extra hours every week to brush up your skills, gain new skills, and get better at your trade.

  • Committed - It’s not easy to become a programmer. It will require a lot of commitment, practice, and more programming, of course.

  • Investigative - You may end up spending days trying to fix a Javascript memory leak, or why your Rails app is running slow and leaking memory. It will require a lot of investigation, research and thinking about every aspect of the application, and it’s behaviour. You will have to read API documents, source code, and so on.

All in all, it’s not going to be easy.

Now, do you still want to be a programmer?

Abbreviation in Ruby

Ruby’s standard library is filled with several unique, non-standard classes/modules, one such module is Abbrev.

Abbrev calculates the set of unique abbreviations for a given set of strings. The following code demonstrates it properly:

1
2
3
4
require 'abbrev'
require 'pp'

pp Abbrev.abbrev(['ruby', 'rules'])

This code produces the following output where all the keys are abbreviated and unique, and point to their respective words.

1
2
3
4
5
{"ruby"=>"ruby",
 "rub"=>"ruby",
 "rules"=>"rules",
 "rule"=>"rules",
 "rul"=>"rules"}

This also provides an extension for an Array, so you can call ‘abbrev’ method straight on an array. The code above will then become:

1
2
3
4
require 'abbrev'
require 'pp'

pp ['ruby', 'rules'].abbrev

I found a couple of use cases of the Abbrev module on Google:

  1. For creating unique labels for a bar graph.

  2. For creating an auto-completer on console, intriguing, right?

Hope this will make you aware of such a nifty module and please share your use-cases with the rest of us.

Cryptic Global Variables in Ruby

Do you know what $! means in Ruby?

Years ago, I was discussing some issue regarding GemCutter (now that makes it ancient in programming age), and we were talking about global variables in Ruby, for example, $; and $/. At the time, we couldn’t really find a place to look them up, even Google isn’t very effective given the nature of the query.

Anyways, while looking through Ruby’s standard library, I found the file English.rb. This library has English names for all the cryptic global variables. For example: $ERROR_INFO represents $!.

If you ever have to look up the English names, which I suggest you do as it makes code easier to read, just refer to that file.

Nested Exceptions in Ruby 2.1.0

With Ruby 2.1.0, one can easily trace the original exception. Previously, on rescuing an exception one would have no reference to the original exception (thrown by a gem/library). There are a couple of gems that can help you keep track of the exceptions, but with Ruby 2.1.0 you can work with nested exceptions without any issues. Here’s some trivial code to achieve the same:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Car
  def self.start
    begin
      1/0
    rescue => ex
      puts "Exception: #{ex}"
      raise StandardError.new "Can't start the car"
    end
   end
end

begin
  Car.start
rescue => ex
  puts "Cause: #{ex.cause}"
  puts "Exception: #{ex}"
end

This will produce the following output:

1
2
3
Exception: divided by 0
Cause: divided by 0
Exception: Can't start the car

You can play around with the code yourself. It’s not as sophisticated as the gems out there, but it’s getting there.

Aspect Oriented Programming

I was looking into Ruby’s TracePoint class recently. TracePoint is an objectified Kernel#set_trace_func method. TracePoint was added in Ruby2, but before that there was a gem that had same function as TracePoint class. Surprisingly, it was also called tracepoint.

Anyways, TracePoint is not the scope of this post. This post is all about AOP, or Aspect Oriented Programming.

Wikipedia defines it as “aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. AOP forms a basis for aspect-oriented software development.”

There are couple of things worth noting, Modularity and Cross-cutting concerns.

Modularity

In English, Modularity means based on modules, easily assembled, or repaired and the reason it’s easily repaired is because modules are self-contained and talk to each other via a defined interface. Interface could be hardware pins, RAM slots, or intangible ones, defined in your Ruby or Java class.

In Ruby world, modules and modularity is the go-to thing to achieve separation of concern. You got a piece of code that is used in two different places and has no state of its own, just create a module to be included/extended or prepended.

Cross-cutting concerns

Cross-cutting concern can be defined as any piece of code that’s more widely used across the application, for example, logging, security, or authentication, perhaps. Something, like a before_filter in Rails controllers that’s applied to a set of actions.

There are libraries that one could use to achieve same and even more than before_filter functionality outside of Rails. The one that I briefly looked at is called Aspector. It provides a lot of examples as well just in case you are stuck.

Why not just use Ruby Modules?

Ruby modules are similar but not exactly same as the AOP concept. One important difference is that you can apply an aspect (aspect is the piece of code with common functionality, like a module) to a class from outside, without opening the class. Here’s some aspector code snippet to elaborate the point:

TestAspect.apply A

Here A is the class, and TestAspect is the aspect. As you can see, you can just apply it from outside. Sorry, not very clear, but I didn’t want to tie the concept to a particular library implementation.

One good use case of using AOP concepts would be with something like debugging, for example, a user performed an action and you want to check the log for parameters that are getting passed in to methods, or what methods are getting called when certain action is performed. But, that’s what TracePoint does, right? Well, it definitely allows one to hook into the events and print debugging information. With AOP, one can create more focussed debugging. Imagine, a request going through Rails stack will hit a lot of methods and you don’t want to enable tracing and then having to go through a long console output.

These are just some of the initial thoughts I had on reading AOP and TracePoint. Hope this post will encourage you to investigate and learn more about these topics.