Tuesday, May 31, 2016

ZingChart



I'm involved in a project that requires me to create interactive charts and graphics. After doing a lot of research I found out a great library for this: ZingChart (http://www.zingchart.com/).

It renders graphics in HTML5 canvas, SVG and VML. It is easy to use and well documented. I strongly recommend for those who need graphs and charts in a fast and practical way.


Friday, May 27, 2016

Is Rails a cul-de-sac?



A lot of people know and respect Piotr Solnica. His blog (http://solnic.eu/) is really good. He is a core developer to a number of Open Source Software projects. And he was a RoR user.

I say he was because last week Piotr wrote this interesting article criticizing Rails and stating clearly he is leaving the Rails and the Ruby communities. His article mentions lots of technical reasons why he believes Rails is not good. And any average-to-good software architect is going to agree with most of his points.

Rails is not just a meta-framework for Ruby language. Rails is also, and mainly, a set of decisions made to create an easy environment for web developers to create their applications. Of course, not all the decisions taken by the Rails team are based on the best architectural techniques.

Some of these decisions are, in fact, very bad, although they seem very good at first sight. And I have a great example to show this: scaffolding.

When I first saw a Rails presentations I got fascinated with scaffolding. Imagine that! Creating a whole set with Model, Controller and all needed Views with a single command! This fascinates new users, for sure, but it is not good. Now that I am an experienced RoR developer, I seldom touch scaffolding. In fact, I only do that when teaching Rails to someone else. And even so, clearly stating this is not a good decision when working with a real project (http://stackoverflow.com/questions/6735468/why-do-ruby-on-rails-professionals-not-use-scaffolding).

And this is only a "visible" point, in the sense scaffolding is something Rails users really see happening. If you enter Rails code (https://github.com/rails/rails) you'll surely find lots of points where practical matters replaced good architecture.

This is one of the reasons why Rails is so heavily used nowadays. Most developers are looking just for a fast and (relatively) safe developing tool. They are not interested in the architecture quality behind the scene. In fact, the common web developer is not even qualified to understand this architecture completely. But this common web developer loves Rails exactly because it is practical and fast.

Piotr also says that, after six months, Rails applications may turn into a maintenance hell (the words are mine, but this is what he meant). My experience says he is right, but not for the right reasons.

Most Rails developers are looking for a fast tool because they are always in a hurry. They are always behind schedule. And this means they are not going to do the elementary procedures to keep their systems easily maintained. Like documenting! I've studied thousand of lines of RoR code in the last few years, exactly because one of my skills is fixing systems when they are broken. I haven't seen many inner documentation. And I'm not even going to mention external documentation. In these days of Agile-all-around, nobody cares about creating lots of diagrams and text descriptions. Things are discussed on GitHub issues or Trello boards and this is all the external documentation you'll find out there right now.

I think Piotr has a great point when he says that Rails core team is a bit "bad mannered" (here again this is my interpretation of his words). I noticed that long time ago and this is one of the reasons why I never got interested in contributing to Rails directly, although I keep an eye on the development almost daily. If you do the same you'll frequently see what I mean. People create pull requests and Rails developers reject them with no more explanation than "We believe this is not useful". Not a great courtesy, except from one or two of them. This strongly discourages people to contribute. When your pull request is rejected but you receive a good explanation telling you why it was rejected, you feel that they care about your contributions at least, even when they don't use it in the software. But if one says only: "Not useful" most people got upset with this approach. I don't really care. I have no personal feelings when it comes to work. But I'm not a good example, since I've been in this market for the last 32 years and then I had enough time to learn that: a) My code is not the best code in the world; and, b) Rejecting my code is not rejecting myself. Some people do confuse these things and react really bad in these situations.

Fabio Akita wrote a great answer to Piotr's article: http://www.akitaonrails.com/2016/05/23/rails-has-won-the-elephant-in-the-room

I suggest you to read both articles before taking a decision about what side you're going to line up with.

After that, I'd be really pleased in reading about your position on this subject in the comments.

See you soon.

Saturday, May 21, 2016

Adding ActiveRecord Relations



DISCLAIMER: This post is based on a true story. All coincidences with real situations or real people are completely intentional.

I am developing a small web system to a customer of mine. He use it to control the sales in his store. Nothing fancy. Just a few classes. A simple task, indeed. It took me just yesterday and today.

One of the requisites I received was that a certain customer of his store, with id=1, should always appear first in the customer's list, while the others should appear in the alphabetical order. In order to do so I did this at first:


It didn't work. It couldn't work, because it was a stupid idea. Even the most superficial test with rails c would have shown the absurdity of this idea. The variable a stores a single record, an instance of Customer model, while b is an ActiveRecord::Relation. Trying to add these two thing is like trying to add oranges and apples out of a good fruit salad.

When I got convinced of this fact I changed my code to:

And now it worked fine! Now I was adding to instances of the same class, ActiveRecord::Relation.

This kind of code, using the operator + directly saved me the processing time required to do something like:

This turns out to be even more important when you have a big number of records. This block would take a long time to run in this case, while the a + b operation is much faster.

Don't forget to check things at Rails console. You may save a lot of time doing a bit of research there when there is the slightest possibility of type conflicts or some similar thing.

And once more: Don't accept the first code you do as good enough. Always try to find a better way to do the same thing. There is always a better way.


Monday, May 16, 2016

Very funny video



I know, I know... this is a blog about Ruby and RoR. But having fun is never enough and this video about the war between .NET and Java is really great! Hope you enjoy it.


While they fight, we conquer the world for Ruby! 

Good news from Code Climate



Code Climate, the best online tool to evaluate the quality of your code, has good news.

They are making available their Code Climate for Google Chrome extension. This is the link: https://www.producthunt.com/tech/code-climate-for-google-chrome.

Those who want to test this new extension must visit this link here

I'd like to thank Bryan Helmkamp, CEO, and Jenna Smith, Customer Support Lead from Code Climate, for they gave me permission to post this note here. As a Open Source developer I'm a proud user of Code Climate.



Saturday, May 14, 2016

Better algorithms (2)



This is one more article in a series showing how to achieve better programs just by not believing your algorithms are good enough and refactoring them until perfection. Or at least until someone appear with a better algorithm. The first article, for those who haven't seen it, is here.

This time I'm going to talk about another simple problem, counting the most frequent character in a string. This question I gave to my students, generated this code here:

A simple exam of this code shows that we are taking a lot of lines (from 4 to 8) just for initializing the hash of the counts. We can save some code with just a few changes:

Now we are a few lines shorter and much more readable. The inline if helps a lot in readability, because sentences are much more natural with it. Think about it and you'll see that "Do something if this happens" is more natural than "if something happens do something, else do something else".

Making code better in Ruby, of course, is a matter of knowing the core libraries. All this code above is for students. A real code for professionals would be much more like:

As you may see, all that code may be simplified to only three lines. This was possible because we reminded the fact that the Hash has an option for creation that allows you to specify a default value for newly created items. In this case this value was set to zero.

The use of max_by, a method descending from Enumerable class, which is an ancestor of Array, make possible for us to remove all lines from 7 to 15, which is a lot of code.

Friday, May 13, 2016

Methods inside methods



This is not well known, but you may define methods inside methods in Ruby. The following code is perfectly valid and runs.

The output will be

Method alfa
Method beta
Method beta

As you may see, the method beta won't disappear after method alfa finished its execution. In this point, inner methods are different from inner variables. In effect,


will output

Method alfa
1
Method beta
testing001.rb:14:in `alfa': undefined local variable or method `beta_variable' for main:Object (NameError)
from testing001.rb:18:in `<main>'

because beta_variable is not defined in method alfa scope. All the other three puts are going to generate similar errors, since we are using variables out of the scopes they were created.

This is an interesting behavior!

Thursday, May 12, 2016

Better algorithms



Computers are getting faster and faster everyday. Hard disk drives have more capacity now that I ever dreamt thirty years ago, when I started programming. Memories have more capacity and are much faster. Now I don't need to turn my computer on and go to have some coffee while it gets ready to work. This happens in seconds.

This is all very good, but nothing is perfect. You know what they say about that old Chinese symbol called Yin-Yang. There is always something bad inside good things, and always something good inside bad things.



The good part of older computers was the fact we, programmers, had to deal in too much optimization. We had to be aware of every single byte, of every single millisecond spend.

The bad part of new computers is the fact we don't need to do the same. Many people say "Oh, I don't need to optimize that much, because computers are faster now", or then "If the memory is not enough to run this system we may buy some more", or even  "We may upgrade the processor if this one is too slow to run this".

As a general result, many algorithms and data structures are not so thought about as they could be. I'll give you an example in this post.

A student of mine was trying to solve this simple problem: "Given a list of n integer numbers, how many divisors of these numbers are also divided by 2 themselves?"

In order to solve this problem he wrote this Ruby code and asked me to evaluate it.

divisors01.rb

def divide(d,n)
    ((n % d) == 0)
end

def even_divisors(n)
    cnt = 0
    (2..n).each { |d|
        cnt = cnt + 1 if (divide(d,n) && divide(2,d))    
    }
    cnt
end

_n = $stdin.gets.to_i

(1.._n).each { |r|
    _prov = $stdin.gets.to_i 
    puts even_divisors(_prov)
}

As you may easily see, this does the job. It reads the number of elements in the list then loops reading the elements and invoking the method even_divisors who prints the number of divisors of the parameter received who are also even numbers.

But this method, as you may see, may take a lot to run for each number. It loops from 2 to n one by one, which is not necessary, since we don't need to count the odd divisors. Then, we test the divisibility of the parameter n given by (n-1) numbers, but half of the tests are not necessary.

Under my suggestion he changed the code this way.

divisors02.rb

def divide(d,n)
    ((n % d) == 0)
end

def even_divisors(n)
    cnt = 0
    d = 2
    while (d <= n) do
        cnt = cnt + 1 if divide(d,n)
        d = d + 2
    end    
    cnt
end

_n = $stdin.gets.to_i

(1.._n).each { |r|
    _prov = $stdin.gets.to_i 
    puts even_divisors(_prov)
}

Now we are much better. Instead of that range block (2..n) we are looping from 2 to n in steps of two, testing only the even numbers. This, of course, will reduce running time. But I insisted with him it is not optimal yet.

The fact is, we have a method named divide with a single line and we may move this line to our looping block, avoiding an unnecessary method call, this way:

divisors03.rb

def even_divisors(n)
    cnt = 0
    d = 2
    while (d <= n) do
        cnt = cnt + 1 if ((n % d) == 0)
        d = d + 2
    end    
    cnt
end

_n = $stdin.gets.to_i

(1.._n).each { |r|
    _prov = $stdin.gets.to_i 
    puts even_divisors(_prov)
}

We run a simple benchmark to see the differences of performances of these three codes. This is the result:



As you may see, the first code takes 2.5937 times the time taken by the second. And when compared to the third it takes 3.8604 times the time the third method takes.

You may also see that when you compare the second method with the third, it takes 1,48837 times the time the third takes. This is due to the method call. We seldom think about what happens when we call a method. There are a lot of tasks to be performed and these tasks take time.

Now you may ask me: "How may I know when I should create a separate method or when I must keep the method code inside the loop?"

It is easy to know. If the code is simple enough not to make the logic inside the loop too complex and it will be executed just from one point, keep it inside the loop. Create a new method only when this is needed to keep the DRY principle.

Thursday, May 5, 2016

Great news about Font Awesome



Those who love Font Awesome like me will receive this post with great happiness.

Dave Gandy, from Font Awesome, told me this morning that the Beta Release of Font Awesome CDN is already  on-line! Now you may have all those great icons in your site with a single line of code. And also have many other advantages.

If you wanna know everything about it, just navigate to this article here and see for yourself.




Upgrading Rails version



I was doing some maintenance in an old application, still using Rails 4.2.4, and decided to move it to Rails 4.2.6.

I updated my .ruby-version to contain the string 4.2.6 and then update my Gemfile accordingly. Everything was fine and then I executed my bundle install.

This was the result:

Fetching gem metadata from https://rubygems.org/
Fetching version metadata from https://rubygems.org/
Fetching dependency metadata from https://rubygems.org/
Resolving dependencies...............
Bundler could not find compatible versions for gem "actionpack":
  In snapshot (Gemfile.lock):
    actionpack (= 4.2.4)

  In Gemfile:
    rails (= 4.2.6) was resolved to 4.2.6, which depends on
      actionpack (= 4.2.6)

    sass-rails (~> 5.0) was resolved to 5.0.4, which depends on
      railties (< 5.0, >= 4.0.0) was resolved to 4.2.4, which depends on
        actionpack (= 4.2.4)

    sass-rails (~> 5.0) was resolved to 5.0.4, which depends on
      sprockets-rails (< 4.0, >= 2.0) was resolved to 3.0.4, which depends on
        actionpack (>= 4.0)

What it says is there is a conflict between the new Rails version and the old auxiliary gems like ActionPack.

When this happens you may run bundle update, of course, but there is another solution. You may just delete your Gemfile.lock and run bundle install again.


Wednesday, May 4, 2016

Application wide partials



Just a short tip for my readers about application wide partials, those partial like headers or footers appearing in all your pages.

Sometimes our first idea is to place these partials under a certain controller's views. For instance, I have a Site controller

class SiteController < ApplicationController

  def homepage
  end

end

such that in config/routes.rb we have

root 'site#homepage'

and in app/views/site/homepage.html.erb we render a partial named footer with

render 'footer'

Our first idea may be storing footer's contents inside app/views/site/_footer.html.erb, but this is not a good idea. If we do so, trying to render this footer from other controller's view, say Admin controller, would result in an error. To avoid this error we would have to do it like

render 'site/footer'

Nothing so difficult in this, of course. But there is a less known way to do the same without this.

You may create a directory named app/views/application and all partials under this directory will be within the scope of ApplicationController, Thus, they may be rendered wherever you want, disregarding the controller whose method is being executed.

In fact, in my opinion this folder app/views/application should be created by default when the application was created with rails new [application_name].