Thursday, December 29, 2016

Programming languages 2016

As I said in this article here, I find it strange when I see posts like "The most used programming languages of 2016" in the middle of June or July, with half an year still to go.

But now it is December and finally Tiobe published the ranking for the last month of this year. Here it is, for those blessed ones who like to see by themselves. But this image below will be enough for some considerations.



Java, as always, is in the top of the list. And Java is not going to fall from this top position in a predictable future. It is solid, stable and passes an image of confidence. Java will still be the top language for a long time, I think.

It surprises me to see Visual Basic .NET going up! Well... it is not a complete surprise, since I always bet on the side of human stupidity. Visual Basic is not a good language at all. And the fact it is still attractive is only a sequel of two facts:  Microsoft's power and programmer's foolishness.

Assembly language still in a rise, as I predicted in previous articles like this one. Internet of Things is a reason, I think. It is growing at a fast pace and requires microcontrollers. Assembly will always be the language for these things.

PHP is still falling down. I regret to see this, for emotional reasons. I helped this language to start and it is a bit sad to see its downfall. But it is a sequel of PHP's irregular growing and disorganization.

Javascript is steady, and this surprises me. With so many great tools like Angular and React, I was waiting to see it growing stronger, not just steady.

Last, but not least, Ruby is falling in this ranking. And it is not the first time. But those who love this great language, like me, don't need to worry. A new tool is about to appear, my Emerald Framework, which will help Ruby to revert this situation.

Well, just two days to the end of 2016. Not an easy year for me, but it passed away as always. And I survived.




Thursday, October 13, 2016

The "Eight Queens" problem solved in Ruby

Here is an interesting solution for the classic "Eight Queens" problem.

It is easy to learn that, in chess, a queen moves like this:


The "Eight Queens" problem consists of trying to place eight queens in a 8x8 chessboard, in such a manner that none of them may capture other queen.

After thinking a while, I solved the problem with this small program.



I'd like to call your attention to the fact I represented the chess board with a Hash, not as an 8x8 Array. And you may also notice that the keys in this Hash are arrays! Arrays with the coordinates of the position. The values are either 0, for an empty position, or 1 for an occupied position.

In my old Dell Vostro Duo Core I used the command

$ time ruby eightqueens.rb

to run this program and got the following time statistics:

ruby eightqueens.rb  0,62s user 0,10s system 49% cpu 1,453 total

Very fast, don't you think? I dare. I double dare someone to post a gist at GitHub with a faster solution!!! LOL

I'll be waiting! And I'll be back!!!


Monday, September 19, 2016

Emerald Framework

Emerald Framework is up and running!

Those who want to take a look at the code may visit: https://github.com/EdDeAlmeidaJr/emeraldfw (and please, don't forget to star the repository, please!).

But if you want just use it, please watch this video showing how to install it:


Saturday, September 17, 2016

I'm back, and Emerald Framework is published!!!

I'm really sorry for being away for so long, but I was very busy in the last few days. And the reason for this was the fact I was dealing with Emerald Framework.

As I posted here last month, I'm building a web development framework. And I hare the pleasure to announce it was published this afternoon!

Emerald Framework at Github:

Emerald Framework at Rubygems.org:

Of course it is still in ALPHA version and not all features are ready, but I hope that you'll all help me to make it better suggesting new features, pointing me the errors and so on. And developing too! All forms of contibutions are welcome!

I've also created a blog to discuss it and I invite you all to visit there, posting suggestiong and commenting anything you want: http://emeraldframework.blogspot.com.br/

I really hope you enjoy Emerald Framework.

Tuesday, August 23, 2016

SandCage

I seldom talk about services here. I only do this when I really believe the service maybe a good thing. And this is the case of SandCage, a recently launched startup which, maintaining a quality service, will be a great success, I believe.

I suggest you to pay a visit to their website and see for yourselves:
 

Saturday, August 20, 2016

Emerald Framework - Guidelines

After the post "MVC or not MVC?", many people wrote me to ask about Emerald Framework. I don't intend to talk too much about it before the first release is available, which is scheduled to next weekend, but I decided to post here about the guidelines I followed in the development, as well as about some special characteristics of it.

The first interesting point about it is the fact it is written in Ruby and will be distributed as a Ruby gem. But it is not limited to Ruby. In fact, it's slogan is

Many programming languages
One framework to rule them all
One framework to find them
One framework to bring them all
And in the web bind them

Yes, I love Tolkien's "The Lord of the Rings"! And the releases will be named after characters of this books. This first release will be named "Aragorn".

We are so used to the fact that all frameworks are tied up to one language that we tend to forget that a framework is not language, but methodology. It is more connected to the procedures, the flow of development, than to an specific language. As the name says, it is a frame of reference for development. A set of tools and rules, a specific architecture. Stealing a few words from Fabio Akita, in this article here, "a coherent, opinionated full-stack".

So, Emerald Framework will be written in Ruby, but it will make possible for its users to develop using Ruby, PHP, Python... and other languages in the future, if the community around it create new sets of generators for other languages. As long as they keep the development rules in mind.

Yes, because Emerald has rules! I'm going to tell you about some of them, the main ones.

  • Be simple, without being simpleton. I value simplicity. My ideal of perfection is not something we don't have anything to add, but something we don't have anything to take away. Something like a Japanese Zen garden.
 A Japanese  Zen garden

One of my criticisms about PHP language is the fact they inserted too many things in it's ecosystem and it ended up as a big mess. Similar what good old Richard Stallman did to Emacs. Hell, that thing may even act as psychologist, if you need one!!! And believe me, if you are ready to discuss your mental condition with a computer program, then your really need a psychologist!!!

 Richard Stallman
  • A total separation of (Ruby | PHP | Python | ...) code and views. As I said in the above mentioned post, I don't like HTML code being server-side processed to detect special tags, like ERB does in Rails. First of all, this impacts performance. Anyone who dealt with configuring Apache to run PHP, as I did thousands of time in the last twelve years, knows what happens to performance when you say to PHP module to parse all .html files instead of just .php files. As far as I'm concerned, the only acceptable programming language one may write within HTML code is Javascript.
  • Server serves data, not pages. One of the sequels of my above mentioned post was a comment done in a LinkedIn group by a programmer. He said I was making no sense at all when I said servers shouldn't serve HTML pages. It surprises me to see people thinking like that, when I've had so many talks with senior programmers and software architects about just the opposite in the last few years. The objective of a web server is not necessarily serving HTML pages, but serving 'things' for the web! If fact, in the last few years people are doing huge efforts to avoid this: AJAX; data-aware components reloading just pieces of data when data changes; push technology; libraries and frameworks like knockout.js, ember.js, react.js and others. This is why I got surprised to see that some people still haven't got the spirit of this movement. When one transfers the HTML creation to the browser level, the web also profits from this, with a massive traffic reduction. And if you do it smartly, your pages will load faster.
  • Forget MVC. This was another interesting sequel of my post. I was in a skype call with a customer of mine and one of his programmers. We entered this subject of Emerald and I mentioned that Emerald wasn't MVC. The guy asked, as if he was surprised: "If it is not MVC, then what?" I felt like if MVC were the only thing people knew about web development standards now, and this is absurd. There are lots of other standards, and some of them are obviously better to web development than MVC. Then, why is MVC so popular? Why, for instance, Rails adopted it? The answer is quite simple, indeed. It works and organizes things, then it is better than no standard at all. If you doubt what I'm saying, maybe you'll change your mind reading these articles.
  • Loosely coupled components. A simple implementation decision helps Emerald to have its inner parts, its inner components, loosely coupled. We have no special data type being passed from one component to another. We use JSON extensively to this. Adopting a widely used public standard, not a proprietary one, makes Emerald's components easy to replace in future releases and able to be used by any library capable of sending/receiving JSON. I know that it is not usual, these days, to think about the future, to plan for future releases. YAGNI, "You ain't gonna need it", they say when we talk about planning a bit more. And I tell you that this lack of planning is one of my usual sources of humor, every time I see a team involved in an extensive refactoring due to the fact they needed to perform some change that could have been predicted with a few more hours of planning in the very beginning of the project.

 There are certain moments when worse is better.
But generalizing this as a immutable truth is as stupid as any generalization.
  • Focus on DRY. We base our development in small components made of Javascript in the UI/UX and of [Ruby | PHP | Python | ...] in the back end. Both parts are small, clean and independent. Both very easy to reuse in other parts of the systems created with Emerald. This is a great help when it comes to enforce the DRY principle. We don't need to repeat code because we made it very easy to reuse code wherever we need to.
 Repeating himself didn't help Agent Smith
  • Provide archetypes. Those Java programmers who are used to Maven know how easy it is to start a new system when there is an appropriate archetype to model it to you. We are going to enforce among our users, and provide tools for, people uploading archetypes for many types of applications to Emerald servers. We believe we may have an easily accessible bank of solutions to help Emerald developers to do things quickly and easily, without the need to rethink solutions that are almost always based on the very same basis. Those who created a blog using a framework, for instance, know that all those who do this create the same classes, with the same names and almost the same content. Having archetypes is taking code reuse to a new extent in web development. And if you need more than the usual, go ahead and take the archetype as a head start and improve what you need.
  • Your app is completely disconnected from Emerald. If you want to know why I mention this, open this great article by Piotr Solnic, "My time with Rails is up", and search form ActiveCoupling inside it. Emerald does the perfect separation among the framework and the app. I'd like to thank Piotr, for he called my attention to this problem, helping me to avoid it in Emerald.
  • Emerald is SEO friendly. SEO techniques are very important today. Thanks to a gem I developed and to a simple routing process, it was easy to make Emerald SEO friendly.
  • Have a great CLI. A great command line interface has always been a must for me. This is something that attracted so much users for Rails. I opted for Slop gem to help me build this CLI.
I believe this is enough for now. If anyone has questions, suggestions or criticisms (which are always welcome), please send your ideas to

emerald.framework@gmail.com

and I'll be pleased in discussing them. I'm also looking for beta testers to Emerald and if you want to take part in this project helping the tests, I'll thank you very much.

Thursday, August 18, 2016

Tiobe Ranking of programming languages - August/2016



This is the new ranking of programming languages published by TIOBE (http://www.tiobe.com). It is updated till August/2016.

Everytime I post this ranking here (and I've been doing this every month) I got a lot of strange reactions. People say things like:

"I am a Go programmer and I know Go is not the last language in the world."

or 

"Of course there are more jobs for Ruby than for Java. I've been searching for a Ruby position and I noticed this."

Then, let me explain one thing. Or else... let TIOBE explain itself. This is a link to the page where TIOBE explains this ranking: http://www.tiobe.com/tiobe-index/programming-languages-definition/

Then, before calling me names or cursing me and my seed, please read the explanation to understand what the ranking really means.

I'm not a radical for any language. I love Ruby, but I also love Java, C, Object Pascal and LISP. And many other languages. Because what I really love is programming. And, as a matter of fact, I strongly believe in two things:
  • There is no "best programming language". It all depends on many factors, like what you are using it for and your knowledge of it.
  • The best tool is the tool you know better.


Tuesday, August 16, 2016

MVC or not MVC?




I've been away for a long time, without posting anything here, and I beg your pardon for that. I've been too busy with my life-project, the Emerald Framework. This framework will be the next good thing in web development. I'll talk a bit more about it soon. But those very curious may just drop me a message at emerald.framework@gmail.com and I'll send some material about it.

I'd like to talk to you about MVC. And the reason for that is exactly the fact I was talking about Emerald Framework with two people yesterday night and I got really surprised because when I said Emerald wouldn't use MVC  one of the guys (a developer!) asked me in surprise: "If it is not MVC, then what it is?" And he asked this question as if he never heard about other patterns for web development.

This moment I realized how MVC turned out to be popular in the last few years  and how people forgot about other patterns, believing MVC is kind of a "magical solution" to all problems.

Then, let me tell you some point about MVC people tend to forget:
  • MVC is far from being the unique pattern available. We have lots of them. In fact, here we may use that famous quote by Andy Tanenbaum: "The good part of standards it the fact we have so much of them". This ironic quote is oh-so-true when we talk about web development patterns: HMCV (Hierarchical MVC), MVVM (Model-View-ViewModel), PAC (Presentation-Abstraction-Controller), MVP (Mode-View-Presenter), NO (Naked Objects)... I could continue for a long time naming other patterns, but I prefer to let you free to research by yourselves visiting this link  here.
  • MVC is usually a BAD solution when it comes to performance, at least when compared to other options, but this is not MVC's fault. The fact is MVC frameworks were designed to favor maintainability  and readability, not to favor performance. If you really like MVC and is worried about performance, I suggest you to write your own MVC implementation designed for this.
  • MVC is not a good choice for small applications. It is counter intuitive in these cases. You will work too much to have a single page running with MVC, when compared to other options. In fact, if you have an application with only two or three pages, forget all you heard about patterns and code this yourself, in you own way, putting all possible frameworks aside.
  • MVC provides separation between code and presentation, but not as much as it would be possible. In fact, this is one of the questions I specially addressed when I was writing Emerald Framework. I just don't like ANY kind of Ruby (or other language) code mixed with my HTML code. ERB, for instance, is not a good choice to me. I don't like those <%= %> tags mixed with my HTML code.
  • Most MVC frameworks are going to force the web server to perform the inconvenient task of serving HTML code. It's just me or there are others here who believe a web server should be reserved to more noble tasks, like producing dynamic data? This is an old issue in certain circles: let the browser deal with interface generation, provide just JSON and let Javascript build the interface for you. Isn't this, for instance, the essence of knockout.js, for instance? Among other advantages, you may have not just dynamic data, but also dynamic interfaces, customized to each user.
And you? What do you think about MVC? I would really like to know what your opinion, so post a comment here and speak your mind.

See you next post!

Monday, August 1, 2016

Can't find the 'libpq-fe.h header

This is a very common error when you are make your

$ bundle install

in a Rails project using PostgreSQL. And the solution is very simple.

This error means a certain header is missing when compiling PostgreSQL native extensions. This header is provided, at my Debian 8 Linux distribution, by a package named libpq-dev. Then you just need to do

$ sudo apt-get install libpq-dev

and it will be installed.

When I'm using Fedora (before 22), I just do

$ sudo yum install /usr/include/libpq-fe.h

or, if your Fedora version is 22+, try the same with the new package manager, dnf

$ sudo dnf install /usr/include/libpq-fe.h

I am sure you may find this header for your distribution by using the greatest programming helper of all times, Google.

Thursday, July 28, 2016

PostgreSQL migrations' problem solved

I'm not a great PostgreSQL user. Sincerely, I prefer MySQL nine in ten times. But this is not a matter of quality, but just the fact that I started my life as a web developer with the couple PHP/MySQL and use this database for years. I even took a MySQL certification! Then you may see the personal feelings involved in my personal choice.

But life is not what we want, but what we have. And learning to avoid personal feelings is important, specially when you are working with a team.

And this is exactly what happened to me this week, when I started with a new project named Routely, a tool designed to make a revolution in the area of field services (like House Cleaning, Pool cleaning, Pest control, Lawn Service and Parking Lot Service). It helps companies to keep a high quality level for their services; helps contractors to be safe in execution time and helps people that need these services to receive the best for their money.

Routely is a great tool and it will be available soon. And I'm working with a great team, led by a brother of mine, Alex (https://github.com/AlexVKO).

The project uses PostgreSQL and I had to install it in my home server to perform the development and test tasks. That's when problems started.

I use PostgreSQL frequently, because I've been using Heroku a lot in the last few years. But then, Heroku infrastructure does all the hard work. A PostgreSQL Heroku user just have to avoid interference and everything will work fine. 


As you may see, I specify databases for sqlite3 for test and development in this configuration file, but when it comes to pg configuration I just let Heroku work and do nothing!

The main point is: I'm not used to install PostgreSQL! My fault! 

Then it wasn't a bit strange when, after install it in my Debian 8, I couldn't run my migrations, getting the following error:



This error

-- enable_extension("citext")
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::UndefinedFile: ERROR: couldn't open the extension controller file "/usr/share/postgresql/9.4/extension/citext.control": File or directory not found
: CREATE EXTENSION IF NOT EXISTS "citext"

means I was lacking an extension.

If you face this problem with Debian, there is a simple solution. Run

sudo apt-get install postgresql-contrib libdbd-pg-perl

and have this postgresql-contrib installed. This package has all extensions needed to a smooth run of all your features.

If you are not a Debian user, don't worry. Fedora installs this package as a dependency when you install PostgreSQL, and other distributions probably has a similar package. Google it and you'll surely find. And don't forget other great resources for programmers like StackOverflow.

Thursday, July 14, 2016

Ruby is among the fastest growing languages for two consecutive months

The TIOBE index for July/2016 is already online and you may see it here.

It is not a surprise that Ruby is among the fastest growing languages, for the second consecutive month, having ascended five positions since July/2015.


Assembly continues its ascension. TIOBE people, exactly as I said in this article, claim this is due to IoT. If your toothbrush needs some software, it'll probably be written in Assembly. Speed and code size demand this.



Cohesion



Today it is time for us to talk about more generic things on programming.

We say that a certain method has a good cohesion when it does one, and only one, thing.

I know... I know... this is too abstract! Let's see an example to make things clearer.

Consider the following piece of code

This will print all integers between 1 and 1000 whose sum of digits is 10. An easy task. I only separated it in two methods because we need this in order to better understand how important cohesion is.

If you take a look at these two methods, you'll notice the first one (some_method) invokes the other (sum_is_ten?) to ask if the sum of the digits of a certain value is ten. It passes only the value and receives only the information required. This is the perfect behavior, the perfect coupling between two methods. And this is only possible because sum_is_ten? has an excellent cohesion.  It does only one task, deciding if the sum of the digits in the numeric parameter received is ten or not.

Now let's consider another problem, a bit more complex. Now we need sum_is_ten? returning false when the parameter received is not multiple of four, even if the sum if the sum of the digits is ten. We could write it this way:

Or this way:


In this first way sum_is_ten? has a bad cohesion, 'cause it must decide for two things. But what are the consequences of this fact?

First of all, sum_is_ten? is less reusable. Imagine we had another method, say some_other_method, who also need to know if the sum of the digits of a certain number is ten, but not with this restriction about the number being multiple of four. It can't use sum_is_ten?, of course. In this situation we should write another method to perform this task and we wouldn't be able to avoid certain duplication of code.

Besides, the lack of cohesion makes the name of the method inconsistent.The name sum_is_ten? does not express clearly the goal of the method, as it is the ideal situation.

Of course this example is completely artificial, but it helps us to understand why cohesion is so important.

But there is still a point to be made clear: How to achieve a good cohesion?

Breaking things, is the answer! Separating different tasks in different methods and composing its results. In order to understand this, let's see the ideal  solution to our second problem, the list of all integers between 1 and 1000 whose sum of digits is equal to ten and who are also multiple of four.


As you may see, the ideal solution has a new method to decide if the given number is multiple of 4. This answer is composed with the the answer given by sum_is_ten?. Tasks are separated now, and each method executes one, and only one, task.

See you next post!


Tuesday, June 28, 2016

Why Assembly programming is growing so fast?

Assembly surprised me! In this list I posted it appears as one of the fastest growing programming languages.




What is the reason for this unexpected growth? If i was told by someone ten years ago that Assembly would be among the fastest growing programming languages in ten years, my reaction would be like "Are you crazy?"

But then I started thinking about it and suddenly I understood what one of the possible reasons was: IoT

With all this talk about Internet of Things, there must exist a large demand for device drivers for almost anything in the world, from refrigerators to cigarette lighteners! And Assembly is very good when it comes to this.

Here is my advice for the younger generations: Learn Assembly! It may be fun and very profitable!


Monday, June 27, 2016

Are iOS and SQL programming languages?

Yesterday I published a post here with two lists of the most demanding programming languages. I want to thank you all for reading this post. It had more than 1400 page views and helped a lot to improve my counter! A blog needs visitors!

But this is not the point here. I'd like to talk about the first list, this one here:

One of my readers named Peter Choe asked, very correctly, why SQL and iOS were listed among programming languages.

Well... as for SQL, this last "L" stands for "language". So, SQL is a language in a certain sense. It is seldom used as an "independent language", but it is a language, nonetheless. One could argue that there is no SQL "per se", but only flavors of a SQL concept, like MySQL, PGSQL, PL/SQL and so on. But this won't affect the general fact that SQL is a language.

When it comes to iOS... this is unforgivable, but understandable. The data used to create the image was extracted from indeed.com and there one will find job openings saying "Java Developer", "Ruby Developer", "Perl Developer"... and "iOS Developer". I'm sure nobody counted these job openings manually. A crawler did it, for sure. And if you are a crawler programmed to search "XXXXXXX Developer", you won't have ways to decide that Ruby is a programming language and iOS an operational system.






Sunday, June 26, 2016

Top programming languages 2016



It always sounds strange to my ears when I see this kind of list in June! We have half of 2016 to happen and people are already declaring things for the whole year, as if it had already finished.

But here we have another list of the top programming languages in 2016:


It includes an image, with data extracted from indeed.com:


Good news is that Ruby and Rails are there. Bad news is that they are in the last position! But don't despair, because we have this other list, extracted from http://tiobe.com. This one is updated till this month and if you want to go there to see for yourself, this is the link.


As you may see, Ruby jumped from the position 16 to the position 10! This is really good news.

On the other hand, languages like C#, Objective-C, Delphi/Object Pascal and COBOL are going down every new month. A good message for those who intend to spend time and money with them: Don't do it! Pick another language!




Thursday, June 23, 2016

USB Wine - Funny video



Balance is as important in personal and professional life as knowledge and technique.

From time to time you have to stop a while, walk, have some chat with your family (those people living in your house, that you only notice because the noise they make disturbs your programming activities...) and laugh! Laughing is very important.

This is an old video, but I always laugh a lot when I watch it!


Hope you enjoy it! And please, post in the comments other funny videos. Help get some good laughs too!

See you next post.

Implicit (and bad) type conversion



Sometimes it is interesting to know what happens behind the scenes when you are programming. The way the language you are using behaves under certain circumstances.

Someone called Keith L. post the following code in a StackOverflow question (If you visit this link, don't forget to upvote my answer there. Help me build a good reputation there.) yesterday night, asking where was the type conversion, because he could see none. The code supposedly gets a string with many words and returns the longest word in the string.


Just because you can't see something, it does not mean it is not there. Sometimes things are happening behind the scenes and this is one more reason to learn well about the behavior of your language and/or framework.

The problem here lies in the fact Keith L. is assuming (wrongly) that the index of the array is passed to the block, not its elements. Then, when this method receives a string like 'We are developing a method to find the longest word in a string', in the first pass of the each block the value of the inner i variable  is 'We', not zero as he was assuming.

So, when he writes the test if sen1[i].length > sen1[grt].length he is, in fact, doing if sen1['We'].length > sen1[grt].length.

Arrays in Ruby are always indexed by integers. When he tries to get the index of an array using a string, Ruby says this is impossible because this would mean an implicit conversion of a string type to integer type. So, you cant see the type conversion, but it is there!

What would be, then, the correct way to perform this task?

Changing Keith's code just a bit we could have it running.

As you may see, we just changed a few things:

  • The name of the method was changed from LongestWord to longest_word. This is not causing the error, of course, but it is kind of violating Ruby's naming conventions. The first letter in uppercase is reserved to constants and class names;
  • The regular expression used to split the string into word is not necessary. Split does it correctly with just a space (" ") passed as parameter. And a good rule in programming is: Take away unnecessary things; and,
  • The most important of all, the cause of the error, we changed from each to each_index. This will do exactly what Keith wanted in the first time, passing the index, not the element of the array, to the block. Changing this the code runs fine.
Runs fine, of course, but it's not good yet. Keith would still be spending ten lines of code to do something that can be done with three lines.


This is the real Ruby style! And if you want a good exercise to improve your Ruby skills, try to write things in just one line as much as you can. Remember that all things in Ruby are objects, even the return values of the methods. Then you may concatenate operations like in the code above. You know the result of str.split(" ") will be an array, so you may use the max_by method directly on it. You don't need to store this result in a variable and then to use max_by on this variable.

Learn the Ruby way and your code will be shorter and better.

See you next post!

Monday, June 20, 2016

HTML code inside a link in Rails



This is quite simple, indeed, but I see many people asking about this topic in StackOverflow and then this post may be of some help.

Let's see how we may create a link wrapping some HTML code, like this:


We tend to forget that the <%= link_to %> may start a block if you append a 'do' at the end of it. then we may do

It is even possible to mix image and other HTML elements in your link, doing something like this:

As you may see, Rails offers many possibilities if you need complex links. But remember that HTML specification won't allow some elements inside a <a></a>, although most browsers will render almost anything you imagine. And some things you can't imagine too!

To see a good example of this feature, visit this StackOverflow question and see my answer there.

See you next post!

Saturday, June 18, 2016

Building native extensions for Ruby gems



I decided to write about this because I visit StackOverflow everyday and this is one of the most common questions about RoR there.

When you run bundle install in your application directory, you will see something like this:



You may notice that we have two kinds of installation messages. The first, and more common, says only

Installing <gem_name> <gem_version>

while the other says

Installing <gem_name> <gem_version> with native extensions

This is the installation where people use to have problems sometimes. But don't despair!

It happens that some of these "native extensions" are written in C and you need to build them in your machine before using that gem. And most of the times this is happening just because you haven't installed all development packages needed to build C programs.

Once you have all the tools needed to build programs in your computer, everything will be alright. Well... most of the times!

Let's consider two different situations: 1) You are a smart developer and uses Linux or other Unix-like Operational System in your computer; 2) You use any flavor of Windows in your computer because you haven't learned anything better.

1) You are a smart developer and uses Linux or other Unix-like Operational System in your computer

If this is your case, the solution is very simple, indeed.

Just find out in your distribution the package group containing the development tools and install it.

In the Debian box I use mostly, I just have to do

$ sudo apt-get --install-recommends install build-essential

This command will install all build tools needed and after it you'll run your build install perfectly well, if nothing else is wrong with your installation.

If you use Ubuntu, it's just the same. Ubuntu is a Debian-like Linux and most of what applies to Debian will apply to it too.

If you use Slackware Linux and you have installed it FULL, you won't have problems building anything. Slackware contains all the packages needed. If you haven't installed it full, just re-run the installer and install all packages from "D" series. This "D" stands for development and this group contains everything you need.

If you use Fedora, just run

$ sudo dnf groups list

and you'll see a list of groups of packages. Install all those groups for development and you just can't fail. You may install a group doing

$ sudo dnf install group "group_name"

with group_name being the full name of the group desired. Cut and past from the list to be sure.

I use these three Linux distributions mostly, then I'm not sure about yours if it's not among these three. But don't be lazy and do a little research yourself and you'll soon find out how to install your development packages, whatever your distribution is.

2) You use any flavor of Windows in your computer because you haven't learned anything better

The best to do here is moving to Linux and going back to (1) above. If you don't want to perform this radical change at once, try at least install a Linux Virtual Machine in your computer with Oracle VirtualBox and develop using this VM.

The main reason to tell you this is the fact Windows is not made for RoR developers, as I explain in this article here.

But if you insist in using Windows, there we go...

Your best choice is visiting  http://installrails.com/ and do everything listed there.

The second best is installing DevKit after having used RubyInstaller.

In both cases you'll have problems. Versioning problems mostly. It happens that the libraries these two solutions offer are seldom updated to the latest versions of Ruby and Rails. Maybe you'll have to make some changes to your code in order to run it, putting aside the newest Ruby resources. This is never a good idea.

Well... here we are. I hope this helps you when having this problem in installing gems with native extensions.

See you!

Friday, June 10, 2016

Rails on Windows



We all know how difficult it is to run Rails on a Windows environment.

If you visit StackOverflow you'll find thousands of questions related to this fact. It's not an easy task and most of the times it requires non-orthodox solutions.

Recently, after almost five years doing RoR, I needed to run Rails locally on a Windows environment for the first time, because a customer had a requirement for this. His system must be run in his intranet and should be hosted in his Windows server. I had never faced such need before, for all my  systems were internet-based and most of them deployed in VPS servers I configured myself, so I had no problem in doing everything needed.

When this happened, people told me to use InstantRails (in http://installrails.com/) and I did it. It really helped me a lot and I started running my app in a few minutes with this installer. But...

As you may see by this print of InstallRails website,



we are far from having the newest Ruby and Rails versions. And as soon as I started running my system there I started suffering. My system used Ruby and Rails features not available in the versions provided by InstantRails!

After fighting a lot with this, and in fear of having to review all my code to downgrade it to Ruby 2.1.5 and Rails 4.1, I installed a Linux VirtualBox in my customer's server and did the Rails thing as I was used to do. I had it running perfectly in about twenty minutes.

This called my attention out to the following facts:

1) Rails for Windows is a dumb shit! And if it was like this to me (programming since 1984, used to Windows since its first version, doing Rails almost exclusively during the last five years...) I started wondering what a computer newbie would do in my place. He/she would probably give up RoR and move back to PHP, because then he/she would have easy install/configuration with XAMPP, for instance, in minutes!

2) Rails for Windows shouldn't be a dumb shit! After all, we have millions of Windows users around the globe, including many developers. And some of them won't use Linux for nothing, 'cause some of them don't want and some of them just can't install Linux in their work computers.

Even if don't like Windows, we need to improve our efforts to keep RoR running well on it. There are millions of developers like us facing all sorts of trouble with this. And we also have to consider those corporate environments where one can't simply install what he/she likes.

The lack of this is making it hard for the RoR culture to spread in large corporations still tied to Microsoft Windows.

Wednesday, June 1, 2016

Better algorithms (3)



This is the third article of this series {first: Better algorithms, second: Better algorithms (2)}. In the first two I stressed the importance of always try new approaches and the importance of knowing Ruby Core very well.

Today I'm going to talk about another important point to optimize your code: learning about the problem!

The first approach we use to solve a problem is seldom the best one. Common sense is not a good programmer, I tell you.

To give you a good example of what I mean, I'm going to use a simple mathematical problem: Write a method to tell if a number is prime or composite.

We learned at school that a prime number is the one only divided by 1 and by itself. This way, 5 is prime, because neither 2, 3 or 4 may divide 5 with a reminder of 0. But 6 is not prime, is composite, because 2 and 3 divide 6 with a reminder of 0. I keep telling "with a reminder of 0" because we are talking about integer division.

The first approach is almost obvious when you read this description. Given an integer n, we only need to test all numbers between 2 and (n-1). If even a single one of them divides n, then n is composite. It is prime otherwise. Like this:


But if we spend sometime reading a book on Elementary Number Theory like this, we'll find out a theorem stating that the smallest prime divisor of n is not greater than the square root of n. In other words, if p is the smallest prime divisor of n, then p <= Math.sqrt(n). Since we don't need to find all divisors, but only find out if there is one and the smallest is as good as any other, based on this theorem we could make our solution much better by adding a single line:



Why this solution is much better? The answer is time!

Let's do a simple benchmark comparing the to solutions and we'll see.

The first method running on a range from 1000 to 2000

The second method, running on the same range in the same computer

As you may see, we had a dramatic reduction in time. And this would be even easier to see with greater numbers.

So, every problem is worth a small research. You may improve a lot the performance of your programs by doing so.

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.