Categories
ASP.NET MVC C# ruby ruby on rails

How Ruby on Rails Taught me ASP.NET MVC

Before learning ASP.NET MVC, I had the opportunity to learn Ruby and Ruby on Rails. In this post I want to share how Ruby on Rails taught me ASP.NET MVC.

Managing Dependencies

To create a ruby on rails app, let’s type “rails new blog” in a terminal or command prompt. Now that we have a new app, we can see how rails manages dependencies. By running command “bundle install” inside the blog directory, Bundler will install all dependencies inside the Gemfile. It is that simple.

ASP.NET MVC has a similar process. We use nuget to install and manage dependencies. And our Gemfile is named packages.config. We also have a command line to install libraries (Install-Package jQuery).

App Structure

By convention, rails app creates the following directories inside the root app directory:  models, views, and controllers. ASP.NET also creates models, views, and controller but they are created at the root level. Rails gave me a solid understanding on the MVC architectural pattern. Before learning ASP.NET MVC, I knew that models were responsible for the domain’s entities. Views are only concerned with the presentation layer (UI). And controllers manage incoming requests and provide a link between models and views.

Routing

Before learning rails, I was using ASP.NET Forms. With this framework, we were not concern with routing because aspx files were served directly from the file system. There was no configuration done by us. The system just handle it. In the rails world, the route config is located in config/routes.rb. A typical route file might look like:

get "/posts" => "posts#index"
get "/posts/:id" => "posts#show"
get "/posts/new" => "posts#new"
post "/posts" => "posts#create"  # usually a submitted form
get "/posts/:id/edit" => "posts#edit"
put "/posts/:id" => "posts#update" # usually a submitted form
delete "/posts/:id" => "posts#destroy"

In ASP.NET MVC, you will see:


public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",                                              // Route name 
            "{controller}/{action}/{id}",                           // URL with parameters 
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}

They are basically mapping a request to a controller action. After learning rails, it was very easy to me to pickup this new routing thing.

Summary
I’m always recommending that you learn a new programming language, framework, or tools. In my case, I decided to learn a new web framework called Ruby on Rails. Not only I learned a new programming language but also a new web framework. I never anticipated that by learning rails I was also gaining a solid foundation to learn and use ASP.NET MVC.

Categories
Beginners code ruby ruby on rails rubygem unit tests

Read Minitest To Learn Ruby

I continue my quest to master Ruby. Lately I’ve been reading the source code for Minitest. Minitest is a Ruby gem to help developers write unit tests. In addition, you can also use Minitest to write specs and do your development BDD style. The gem also has support for mocking and benchmarking.

Let’s concentrate our attention on the assertions.rb file located at https://github.com/seattlerb/minitest/blob/master/lib/minitest/assertions.rb. Inside that file, we can see that the assert method takes 2 parameters: test and msg. Below is the actual Ruby code.

##
#  Fails unless +test+ is truthy

def assert test, msg = nil
  self.assertions += 1
  unless test then
    msg ||= "Failed assertion, no message given."
    msg = msg.call if Proc === msg
    raise Minitest::Assertion, msg
  end
  true
end

The first line inside the assert method, self.assertions += 1, is increasing the assertions variable by 1. This value is display after your unit tests are run. Something like 10 assertions, 5 pass, 5 failed. Next we see the unless keyword followed by test and a block. Having the comment above this method, really helps us understand what unless is. The unless block will be executed if test is false. Inside that block, we set a default message to msg if msg is nil or false. The next line checks if the msg passed to our method is a Proc object. If msg is a Proc object, msg will be assigned the value returned from invoking the block. To learn more about the Proc class, go to the official Ruby docs. Then we raise an exception by calling Minitest::Assertion and passing the msg variable.

After executing the unless block, we return true.

I believe Minitest is an excellent resource to learn Ruby. It’s a small code base compared to other projects.

Categories
Book Review Change Design Design Patterns Object Oriented ruby

Book Review of Practical Object-Oriented Design in Ruby – Chapter 1

Practical Object-Oriented Design in Ruby

Sandi Metz wrote the book titled “Practical Object-Oriented Design in Ruby”.  As the title implies this book is about object oriented design using Ruby. After reading  a couple of chapters, I decided to share my thoughts about this book but I wanted to do it a little bit different. I want to take each chapter and reflect on the contents. I don’t want to write a book review with a few words. I want to take the time and do it right.

For chapter 1, Sandi starts with the phrase “The world is procedural” but the next paragraph she introduces us to the world as software developers see the world. She writes “The world is also object-oriented”.

I agree with her view of the world as being object-oriented. Everything is an object and they must interact with other objects. She calls these interactions “messages”. I never saw these interactions as being messages. I always saw them as calling a method on my object and getting a response back. I like the word message because it allows you to explain your design to non-technical people.

She also shares the benefits of having a well designed application and contrasting it with the perils of maintaining a poorly designed one. In one hand, you have the joy and pleasure to work in a well designed app and that leads to enjoy the changes introduced by new requirements. You don’t have to modify the entire code base. It is a minimal change. On the other hand, working with a poorly designed application leads to anger and confusion. Imagine having to add a new feature but that change will force you to modify a lot of objects. This is painful and we have experienced the pain with our projects. In the following chapters, she gives us common solutions to these problems.

“Change is unavoidable”, writes Sandi. As software engineers, we know that applications are constantly changing. We must fix this page that suddenly stop working. We got a new requirement for a new feature. We must embrace change and having well designed apps will allow to make those changes without compromising quality or the stability of our project.

She continues with the problem that is introduced when objects and messages know too much about each other. The more they know about each other, the more tightly coupled the design is. This is what she calls dependencies. In the next chapters, she gives us tool to manage these dependencies.

She also introduces Design Patterns and the Gang of Four. If you are an experienced software developer, you must know what Design Patterns and who the Gang of Four are. But to give you a quick refresher, the design patterns are a set of solutions to common software problems. The Gang of Four are Erich Gamma, Richard Helm, Ralph Johnson, and Jon Vlissides. They got together and wrote a book on software patterns in 1995. Both of these resources have helped many organizations with their design. They took time to study common problems and gave us solutions to these problems. These resources are a must have for any software company.

We know that having no design at all is a recipe for disaster. But also having a over-designed application. I have experiences with architects that over-engineered apps and requesting a change required lots of effort. Sandi makes a good point about bringing together design and code. If there is no constant feedback from the designer and coder, this is a recipe for disaster.

Summary

In conclusion, I think that Sandi does a great job introducing her book. She starts with getting our thoughts in place, and asks us to “start thinking in terms of objects”. Once our mind set is correct, she compares a well design systems with one with on design at all. Then she briefly mentions design patterns, the Gang of Four, and how their contributions will help us with our design. I will have a review of chapter 2 next week.

 

Categories
ruby ruby on rails rubygem

Why Ruby’s File.executable? method behaves different between Windows and Linux

Ruby File.Executable

I was working with the RSpec team about some issues with their Windows’ continuous integration build hosted at Appveyor. One of the unit tests was failing on Windows but it was working correctly on Linux. After running only the failing test, I was able to identify the issue with the unit test that was using Ruby’s File.executable? method.

The RSpec team uses Travis CI to run and build their software against Linux operating systems. To run and build their software against Windows, they use Appveyor.

It was strange to me that File.executable? method was working fine on linux but it was failing on Windows. The first thing I did was to read the official Ruby documentation on the File class. After reading the documentation a few times, one word received my attention, “executable”. This is what the documentation says about File.executable?: “Returns true if the named file is executable by the effective user id of this process.”

In the same document, it says “On non-Posix operating systems, there may be only the ability to make a file read-only or read-write.” This means that the executable permission is not available in Windows. It is only available on *nix operating systems.
After reading the official File documentation, I wanted to see if other projects have experienced the same issue. I was able to find a bug report for Puppet Labs titled “Windows File.executable? now returns false on ruby 1.9.” The team decided to close this bug and made minor changes to their unit tests to be OS specific.

We decided to do the same with the RSpec team. Here is the diff view to see the changes.

Categories
code review Javascript python ruby

Improving your code reviews

codestyleCode reviews are an essential practice in any software development team. It allows you to keep your code consistent. It also allows other developers to become familiar with your code changes. Embracing code reviews helps keep your code base healthy.

To improve your code review process, you can do the following:

  1. Document your code style
  2. Allow more than 1 developer to perform the code review
  3. Keep your code changes small

Document your code style

If you don’t document your code style guideline, it is very difficult to keep your code consistent. Some developers might use 2 spaces to indent, others might use 4 spaces to indent. If you have a code style guideline available to all developers, it is easy to enforce it. In addition to be enforced, it is easy for programmers to follow it. You don’t have to open up different files to see the current style guide. You should go to the official style guide for your team or company.

The Python community has documented their code style guide. They created a code style guide under PEP8. One of those conventions is to use 4 spaces per indentation level.

Google has a Javascript style guide. One of the conventions found in the Javascript guide is to always use the keyword var to define variables. Another convention in that document is to always use semicolons.

The Ruby community has also created a style guide. It is hosted at Github and you can see the source here. In contrast to the Python community, they prefer to indent with 2 spaces. See the following example taken from their style guide:

# bad - four spaces
def some_method
    do_something
end

# good
def some_method
  do_something
end

As you can see from these examples, there are code styles available to help us start with our own documentation. If your team does not have their own style guide, then you can at least document that you will follow Google’s Javascript style guide for example.

Allow more than 1 developer to do the code review

After you have your style guide in place, it is very easy to perform code reviews. It is very important that more than 1 developer in your team can review code changes. Sometimes the team lead might be busy or not available and you don’t want your team waiting on that person. They can go to another developer to do the code review. I believe this is a big problem with a lot of open source projects. Some of these popular projects have few developers in charge of the code reviews and many times the pull requests are not handle in a timely manner.

Keep your code changes small

It is easier to code review 1 or 2 files than to review 20 files. If you have a large number of files, the code review takes a very long time to complete. It is recommended to keep your code changes small. For example, if you have database, business logic, and HTML changes, you can break those changes into 2 or 3 code reviews.

Conclusion

If your team performs code reviews in a daily basis, your code base will stay consistent and hopefully bug-free. Based on my experience as a software developer, having a code style guideline, rotating the person performing the code review, and keeping your code changes small, will allow your code review process to be fun and enjoyable.

Categories
Beginners ruby

Get familiar with the Ruby programming language

RubySyntax

Ruby is one of my favorite programming languages. Everything in Ruby is an object. In this article, I want to give a brief introduction to the Ruby syntax.

Strings

In Ruby, you can create string objects in the following ways:

first_name = "Mary"
last_name = String.new 

Now first_name can use the built-in methods available for the String class. For example, we can say first_name.length and we will get 4. Length returns the number of characters contained in that variable. In addition to the length method, the String class has other methods such as upcase, downcase, capitalize.

Numbers

In Ruby, you will encounter 2 types of classes that deal with numbers, floats and fixnums.

Float

Numbers that contain decimals are treated as floats in Ruby. To create a float, you can use:

tax_rate = 8.25
total_amount = 1234.67 

Fixnum

If you need to use integer numbers, you will use fixnum. The good thing about Ruby is that you don’t have to declare the class type. You can just assign any value to your variable and Ruby will handle it.

work_days = 5
work_days.class # Fixnum   

In the above example, typing work_days.class returned “Fixnum” which is the class use to hold integer values.

Array

The official Ruby documentation defines it as, “Arrays are ordered, integer-indexed collections of any object.” You can create Array variables with the following syntax:

a = Array.new
b = [1, 2.3, "test"]

In the above example, a is created by calling the new method on the Array class. b on the other hand is created by using the literal constructor. To get the first item in b, you can use b[0]. Since Array are zero index based, 0 represents the first item in the array.

Hash

A hash is a dictionary-like collection. It is made up of keys and values. The key must be unique. Take a look at the following examples:

h1 = Hash.new
h2 = { "Dallas" => 1, "Houston" => 2, "San Antonio" => 3 }

The h1 variable was created using the new method and h2 was created using the literal constructor. To get the value of the key “Dallas” in h2, you can type h2[“Dallas”]. To get the keys only, you can use h2.keys and this will return an array with only the keys. Similar to the keys method, you can get the values with h2.values. The hash class has a lot of methods that I will go into more detail in a future article.

I hope you find this quick introduction to the Ruby programming language helpful.

Categories
open source ruby ruby on rails rubygem

RubyGem of the week: Rails

RubyonRails

RubyGems is a package manager for Ruby software. It allows you to create and distribute your Ruby packages or libraries. This week I’m covering one of most popular RubyGems, Rails.

To setup Rails in your project, you need to have Ruby 1.9.3+ and RubyGems installed. Once you have met those requirements, you can run the following gem command in your terminal or console windows:

$ gem install rails

To verify that your installation was successful, type “$ rails –version”. It should display the word rails along with the version number. It is that simple.

What is Rails?

Rails is an open source web framework. It was originally created by David Heinemeier Hansson. It is a model view controller framework written in the Ruby language. Some of the companies using Ruby on Rails are: NASA, Amazon, YellowPages.com, Groupon, MadeWithEnvy, Heroku, Basecamp.

So what is different about Rails in comparison to other web frameworks? In my opinion, Rails allows you to build web applications faster because there is less configuration to perform. The frameworks also provides a default project structure. I don’t have to think where to place my models, views, controllers. By default, the framework handles those details for me.

To get started with Rails, I recommend the following resources:

1. The official Rails guide – http://guides.rubyonrails.org/getting_started.html

2. The Rails tutorial by Michael Hartl – https://www.railstutorial.org

3. Book – Agile Web Development with Rails 4

If you want to learn more about the latest developments with Rails, visit the github page at https://github.com/rails/rails. Rails is one of the most popular projects in github with more than 9441 forks, 24492 stars, and hundred of contributors.

I hope you find this brief introduction to Rails beneficial. See you soon.

Categories
Beginners code ruby

Hour of code with Ruby

hour of code with ruby

Ruby is a “dynamic, open source programming language with a focus on simplicity and productivity”. That’s the definition taken from the official ruby site. Ruby is a fun and easy language to code in. Recently, I heard of hour of code, a movement to introduce computer science to million of students.

With that in mind, I want to share an excellent site to learn ruby. Go to tryruby.org and follow the instructions to start writing ruby code. There is nothing to install and you get clear instructions and instant feedback.

For example, you can type “2 + 2” and then press enter in the interactive window, you will see “4”.

Go ahead and have fun learning ruby.