Debugging Ruby on Rails applications

LOGS

This one of the best tools in your toolbox. Logs are great for both debugging and for application analytics.

For maximum detail, the log level should be set to 'debug'. Rails' development mode, for example, defaults the log level to 'debug'.

In Rails you can enable logs by changing the following configuration in the relevant environment initializer file.

 

The available log levels in are: :debug, :info, :warn, :error, :fatal, and :unknown.

Rails logs many events (like requests and responses) by default, but this is rarely sufficient for a typical production application. You will need to also log other information that is relevant to your problem or solution.  Let’s do this through an example.

Ive a web application written in Rails which allows users to register with their email addresses. I also have requirement to allow users to register with valid email addresses. To check validity weve registered with a third-party email validation service. This validation service provides a REST APIs over HTTP, but does not offer a ruby library to integrate with our Rails application.

Let’s take look at the following code snippet.

It works correctly and validates email address but we don't know what was the response sent by the email validation service was.   

We can improve the situation by adding logging statements.

When logging, one must consider storage, security and performance implications, especially when logging to disk. Be cautious about what you log, and how much is being logged.

Using the :debug level will have a greater performance penalty than :fatal, as a far greater number of strings are being evaluated and written to the log output (e.g. disk).

meta-programming

Let's re-use the previous example. In this scenario, let’s assume the ruby client for the email validation service API does not have a logging feature.  

Great. Now in production, we discover that users are unable to register because the email validation service is consistently returning an invalid response. How do we examine the response to determine the cause? Let’s look at the following code.

I’ve temporarily (while I’m debugging ruby client) redefined validate method for EmailValidationService in users controller, adding logging feature to ruby client. This way, I should be able to log the response from validation service. This is one of easiest way to add basic debugging support to third-party gems.

Debugging tools

Special purpose debugging tools allow for powerful, interactive debugging. There are several popular tools in the space, with a great deal of material on their respective sites. Here are three popular debuggers:

Better Errors : https://github.com/charliesome/better_errors

Byebug : https://github.com/deivid-rodriguez/byebug

Pry-debugger : https://github.com/nixme/pry-debugger

Sumit is an engineer at C42 Engineering. If you liked this post, please consider...

/

Ruby Arrays: The difference between copy and dup

On the occassions that I need to clone something in Ruby, that something is usually a custom object, or an array containing custom objects.

Choices

Ruby offers Object#clone and Object#dup as standard features. But what exactly is the difference?

The (now sadly retierd) RubySpec suite is usually the best place to evaluate questions like this one.

As you can see from the excerpts above, at the Object level the difference is that clone copies over the frozen state of the source object, dup does not.

If you're interested in the common behaviours of clone and dup, they are defined in this shared spec.

Arrays

Arrays do a little bit more, of course. Once again, here are the RubySpec specs that show the differences between clone and dup for Arrays.

Basically, clone will (in addition to copying the frozen state) also copy over any singleton methods that have been defined exclusively on the source instance of the Array. dup will not.

/

Boosting Opal's performance with inline JavaScript

"How does it perform?" has been a popular question with Ruby for many years, and Opal, the Ruby to JavaScript compiler, is no exception.

When experimenting with Opal a couple of months ago, I threw together a microbenchmark on top of everyone's favourite recursive factorial and fibonacci algorithms using Benchmark.js in an attempt to answer this question.

Comparison

A few runs on my laptop quickly demonstrated a performance loss of (on average) two orders of magnitude for the Opal/Ruby implementations.

Factorial

Opal#factorial x 270,439 ops/sec ±8.06% (93 runs sampled)

JS#factorial x 23,964,240 ops/sec ±1.28% (94 runs sampled)

Fibonacci

Opal#fibonacci x 10,020 ops/sec ±2.78% (89 runs sampled)

JS#fibonacci x 434,727 ops/sec ±10.29% (80 runs sampled)

Here's the code I used:

Inlining JavaScript

Ruby's backtick operator (or the equivalent %x), which normally calls out to the shell, has no practical use in a browser. Opal reuses it to inline JavaScript in an eminently readable fashion.

The inlined JavaScript implementations of the previous examples look like so:

Lets take a look at what this does to our benchmarks.

RubyWithInlineJS#factorial x 24,201,484 ops/sec ±1.22% (94 runs sampled)

RubyWithInlineJS#fibonacci x 524,180 ops/sec ±1.13% (91 runs sampled)

Woot! That's practically identical to the pure JavaScript implementations.

Conclusion

A neat, inline, JavaScript implementation of an expensive Ruby function or method brings us right back up to the performance of the pure JavaScript verison. In fact, on some runs the inline Opal implementation outperformed the pure JavaScript implementation by a tiny margin.

If you want to run these benchmarks yourself, take a look at the Performance Benchmarks section of the Redson README.

Sidu is a Partner at C42 Engineering. If you liked this post, please consider...

/

Creating Custom ListViews in Android using RubyMotion

While working on a Android app in RubyMotion I wanted to create a layout that is a list of editable key-value pairs like this

list_view.png

Android already has a view to display items in a list called ListView. By default, a ListView can store a collection of values and displays those values in a TextView, which the user cannot edit. So, the list of key-value pairs will have to use a custom implementation.

The default ListView uses an Adapter to store and manage the values in the list. The Adapter in turn contains a collection of items and implements a method called getView. The getView method returns a View for the nth item in the Adapter's collection.

Overriding the getView method in custom Adapter is pretty much the trick to creating a custom ListView.

So, for the custom implementation, the KeyValueAdapter will be a subclass of the BaseAdapter and will override the default getView method. The KeyValueAdapter will also contain an array of key-value pairs that stores the keys and values. Why not a hash of key-value pairs? Because the Adapter needs a to fetch the key-value pairs by index in the getView method.

The KeyValueAdapter will look like this

The source code for the layout is uploaded here.

 

Shishir is an engineer at C42 Engineering. If you liked this post, please consider...

/

Hand Rolling attr_accessor In Ruby

Ruby is a dynamic language that allows us to do great things at runtime. Today, we are going to see how we can use metaprogramming to add methods to an object after it has been created.

Let us create a method my_attr_accessor which mimics Ruby's built in attr_accessor. attr_accessor is used to dynamically create getters and setters for the fields of a class.

We will need to define my_attr_accessor in - please pay attention, this may be confusing - the class Class as an instance method. This makes my_attr_accessor available in all classes as a class methed.

It does nothing at the moment, so we expect NoMethodError to be thrown if we try to use the getter and setter for max_speed.

To be able to run the specs that are present in each of the file snippets below, please make sure that you have rspec gem installed. To run, use the command rspec <filename>.rb

To create a getter and a setter, we are going to use ruby's Object#define_method. This method allows us to add a method definition dynamically, at runtime, to our object.

Now that we have the method definitions in place, we will need to add the actual implementation for accessing and modifying each of the attributes in order to get the specs to pass. For this, we seek the help of Object#instance_variable_get and Object#instance_variable_set.

Object#instance_variable_get allows us to access the instance variables by just sending a string-name of the variable as an argument to it.

Object#instance_variable_set allows us to modify the existing value of the instance variable by sending a string-name of the variable and the value to which it has to be modified.

And there you have it. A hand-rolled implementation of attr_accessor.

Vineeth is an engineer at C42 Engineering. If you liked this post, please consider...

/