I was working with Ruby CSV library parsing code and got this puzzling…

#Error:

undefined method 'encode' for nil:NilClass (NoMethodError)

I know i didn’t defined encode method, here is my code:

contents = CSV.open "students.csv", headers: true, header_converters: :symbol

Curiosity time

So, why my code caused this error?!

I narrowed it down and removed header_converters: method; and it worked. Hoary… This is good, now I know which area is causing this weird error. But… I still couldn’t answer; why this method is not happy with my code or CSV file?!

Reading thorough CSV source code, I see we can optionally pass a Hash to the open method, right?. Here I’m using :header_converters which it’s default value is nil and it’s defined as:

… All built-in converters try to transcode headers to UTF-8 before converting. The conversion will fail if the data cannot be transcoded, leaving the header unchanged.

From that definition I see the method header_converters: failed because my CSV file/data couldn’t be transcoded, that’s why I got nil.

Ahaaa moment

After reviewed my file/data I noticed the first row starts with a comma like so:

(,RegDate,first_Name,last_Name,......)

When I initiate that row with a space before the comma, it worked. The row now looks like this:

( ,RegDate,first_Name,last_Name,......)

Also when I removed both initial comma and space like so…

  (RegDate,first_Name,last_Name,......)

it worked as well; and NoMethodError went away. Hooray.

Good Day!

Usually when I need iterate over different type of Objects say an ‘Array’ I use each method, which is the core of all Enumerable methods.

Lets say I have the following class Student.

class Student  
    attr_reader :first_name, :last_name, :grade
    
    def initialize(first_name, last_name, grade)
       @first_name = first_name 
       @last_name = last_name
       @grade = grade
    end
     
    def to_s
        "#{first_name}, #{last_name}"
    end
end

The Goal

I want to iterate over all students and return a value based on a condition. Below I’m iterating over all students, return students with grade 11 and above and store them in the seniors_students Array.

Initial solution

The fist solution comes to my mind is to use each method.

def seniors(students)
    senior_students = []  
    students.each do |student|
      if student.grade >= 11
        senior_students.push(student)
      end
    return senior_students
end

ramy =  Student.new("Ramy", "Smith", 12)
tomas =  Student.new("Tomas", "James", 11)
gothom = Student.new("Gothom", "Man", 9)
freddy = Student.new("Freddy", "Benberg", 7)

all_students = [ahmed, tomas, gothom, freddy]
 
seniors(all_students).each do |student|
    puts student
end

All what each method cares about is how to visit each elements of the collection and rerun the value to the block passed. But it doesn’t care about what is this collection and how it’s stored, it’s up to us.

Not only that, also using each is not simple. Here we are looping through ‘each’ element, and performing our check. ‘If’ the element meet our condition, add it to an array called senior_students. It works, but it’s long winded, and not very expressive.

A better way

Since we are returning a new Array containing all elements of our collection for which the given block returns a true value (meet our condition), we can use the select method.

In other way, select if what is in the end of the do....end block its true or exist.

Lets see how we can use select.

class Student
.
.
.
  def senior?
      grade >= 11
  end
.
.
.
end
def seniors(students)
    students.select {|student| student.senior? }
end

First we define a senior? method for students with grade 11 and above. Then we return senior? students only within seniors(students) method.

Summary

The above example shows using select is much better. Because we don’t need to create a new array before performing the check, no boilerplate [add the element to the new array] code, and no dirty ‘if’s; it’s just nice expressive clean code reads as English and simple to understand.

Ruby provides nice methods for array manipulation. We have seen each and select which are only a few of Ruby methods. I hope this helps make your code shorter, more expressive and easier to maintain.

Happy coding :)

Good Day!

One of the things I like being a developer is working with the DOM (Document Object Model), more specifically is manipulating and changing it. The normal way to do so is use jQuery. Although its much better than pure JS but still I need to write more code. Recently I’m enjoying work with AngularJS. The framework support so many ‘helpers’ such as directives, filters and other helper comes out of the box for DOM manipulation. One of these helpers is ngHide directive, but first lest defined directives.

What are Directives?

According to Angular DOC, Directives are:

Markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behaviour to that DOM element or even transform the DOM element and its children.

Angular comes with a set of these directives built-in, like ngBind, ngModel, ngHide, and ngView. Much like you create controllers and services, you can create your own directives for Angular to use. When Angular bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements.

What else we can say about Directives:

  • Directive teaches HTML to write new tricks. Such as dome manipulation, data binding, handle events, modify CSS, … etc
  • Most directives are used as attributes. And some are used as new element/tag.
  • Append data to the directive such as data-ng-show to match HTML5 attributes. Doing so you could avoid some browsers complains about Anglular directives.
  • Avoid writing explicit logic or expression in views.

ngHide

One of these directive I want to talk about it is ngHide. It’s purpose is show or hide a given HTML element based on what is been provided by the ngHide attribute.

1
2
3
4
5
<span>Hide:</span> <input type="checkbox" data-ng-model="isHidden">
<br>
<div data-ng-hide="isHidden">
	<span>Name:</span> <input type="text" ng-model="name" />
</div>

When the checkbox element is been selected, the second DIV HTML element is hidden by adding a ng-hide CSS class onto the element. The CSS class sets the element display to none display: none; using an !important flag.

I really enjoy working with Angular, I feel more productive and write concise code, similar to Ruby and Rails. I’ll write more about Angular and it’s magic coming weeks/months.

Until then, Happy coding :)

Good Day!

I was working on the front-end part of a page which requires creating a modal/dialog for a specific section on the page. By default I was thinking about jQuery dialog. I have used it many times, reliable, easy to use and its part of the awesomeness jQuery UI.

Before I start put the modal (coding and design) together, a friend of mine told me about the plugin Colorbox for jQuery. When I read it’s documentation it was interesting to know it has different approach from the jQuery UI Modal. It can do more with less code. Its so customizable with an easy settings form of an object of key and value (similar to hash in Ruby).

I’m only going to cover simp example on how to user Colorbox. Its demos has more information and example for different scenarios.

Here is hot to write/format your code:

	$(selector).colorbox({ key:value, key:value })

The selector could be an HTML Class or ID. Next is the Colorbox object where all the magic happens using keys and values. Colorbox offer lots of awesome properties (keys) with default values you change them to fit your projects’ need.

Lets see very simple example.

<div class="click" href="#boxy">Open Colorbox Modal!</div>
<div style="display:none">
  <div class="box" id="boxy">
    <h1>Colorbox - a jQuery lightbox</h1>
    <p class="description">A lightweight customizable lightbox plugin for jQuery</p>
  </div>
</div>

My simple goal is, when user clicks on the first div <div class="click">....</div> the other div shows up as part of colorbox. You have to have the target div within another div that has display style is set to none. When user clicks on the first div, the target div will pop ups.

Here is the minimum JS code you need to get it done:

$(document).ready(function () {
  $('.click').click(function () {
    $.colorbox({inline:true, href:"#boxy"});
  });
});

In Line 3 I’m calling the object $.colorbox and passing two properties. First one is inline, which is set to true in order to display the desired content (my target div) <div class="box" id="boxy" >...</div>. Second, is passing my target div using it’s ID not class property as a href.

Check out my Codepen page of full example.

Happy Coding, eh! ;)

Good Day!

People sometimes call Ruby, a ‘language that has lots of magics’. I like it’s magic and it’s shortcut that helps to get the job done with beauty and efficiency. One of these magic is Ternary Operator. Since I like to understand why things are named the way they are, lets understand what is the ‘Ternary’ word.

Defination

Ternary is a Latin word, means “composed of three parts”. Wikipedia lists different meanings and examples for it here.

Also Ternary is a conditional operator where it evaluates giving expression and returns a value when it is true or return another value when it’s false. Like so:

  expression/condition ? result if condition is true : result if condition is false

You see, Ternary Operator is simple and more readable, as if you are reading English. Don’t you agree? Check out this simple examples:

Human = true ? 'Human' : 'Robot
human = (true && 'Human') || 'Robot

As we know it is a short versions of if / then statements.

If else example

max_speed = 100
if max_speed = 120
  puts("Slow down, it's dangerous!")
else
  puts("You drive safely.")
end 

The Ternary way

max_speed = 100 
puts max_speed = 120 ? "Slow down, it's dangerous!" : "You drive safely."

OR

max_speed = 120 ? (puts "Slow down, it's dangerous!") : (puts "You drive safely.")

How it works

  • Giving expression max_speed = 100,
  • Evaluate this condition max_speed = 120
    • If its true, output ("Slow down, it's dangerous!")
  • Otherwise/else
    • If its false, output ("You drive safely.")

Similar operator

Ternary operator is similar to the following: language ||= "Ruby". Which you can expand it to language = language || "Ruby" If we have language is set to certain value then it will return that value otherwise its assigned to Ruby.

Real scenario

Here is a real scenario where you can use Ternary Operator. Lets say within your Rails view you want to show the user full name when user is Signed in; otherwise you show ‘Welcome guest”.

Using If else you can write it as follow:

<% if @user_signed_in? %>
  <%= "Welcome", @current_user.full_name %>
<% else %>
  <%= "Guest" @new_user %>

And with Ternary Operator you can say like so

<%= @user_signed_in?  ? "Welcome", @current_user.full_name : "Guest" @new_user %>

I see Ternary operator is short, simple and sweet as one bite chocolate create happiness.

Happy coding :)

Good Day!

While I’m I was working on the designing an existing form, I found it’s been constructed as bunch for input elements except the submit ‘button’. It wasn’t an input or a button element, rather it was a DIV that should have the look and feel for rounded corner button.

The problem

While the user working on filling each input element such as, ‘first name’, ‘last name’… and so on. User can’t click on the Enter key to submit the form. Here is an example for a very simple form:

<form id="contact_form" class="contact_form" method="post" action="welcome.html">
	<div class="first_name">
		<input type="text" name="f_name" id="f_name" class="fn_textbox">
	</div>
	<div class="last_name">
		<input type="text" name="l_name" id="l_name" class="ln_textbox">
	</div>
	<div class="email">
		<input type="text" name="e_mail" id="e_mail" class="email_textbox">
	</div>
	<div class="submit" id="submit_form">Submit</div>
</form>

As you may notice that submit button is a ‘DIV’. Using its ID, a jQuery function triggers it on a ‘click’ event (not the Enter key) and submits the form.

I haven’t faced such a problem like that, because I always construct forms with an input or button element for Submit action.

Solution

In order to give user the ability to click the Enter key on the keyboard to submit a form, I have to attach the key Enter location or KeyCode with a function when its been pressed. I got to know more about key codes from this cool site by @CambiaResearch. It gives you the ability to enter any keyboard key and it displays the key name and key code as well, very neat.

Here is simple and easy solution.

<!-- <script type="text/javascript">
		$("#contact_form *").keypress(function (e) {
  		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
	      	$(this).parents('#contact_form').find('#submit_form').eq(0).focusin().click();
  		}
  	});
</script> -->

Lets speak code. Here I’m saying, when the pressed key is ==13 or its’ keyCode ==13, find id="submit_form", focusin and click it.

Happy Coding, eh! ;)

Good Day!

I wanted to practice RSpec more and feel that joy of TDD. So I start with simple tests aiming to cover and learn more about RSpec. During the practice I learned more about Matcher, Exceptions, missing method and the thinking process of solving an issue using test first.

As you see below I have bunch of tests with Movie. Also I have required the movie file from "../lib/movie.rb"

require_relative "../lib/movie.rb"

1
2
3
4
5
6
7
 
describe Movie do
	it "has a name"
	it "has a list of casts"
	it "complains if there is a bad word in the name"
	it "is favoured if it has a celebrity in it"
end

Although we have nothing written within our spec but we can run it and see all four tests are pending. It always good practise to run our specs to understand the whole picture of our specifications.

Now lets tackle each spec.

1- Movie has a name

In order to test Movie has a name, we should first create an object of that name by creating a new instance of Movie

 
movie_rspec.rb
it "has a name" do
	Movie.new
end

When we call that new object/instance of Movie, it ‘should’ ‘respond to’ us. Luckly Rspec has a matcher for that propose respond_to.

 
movie_rspec.rb
it "has a name" do
	Movie.new.should respond_to
end

Now we should pass a ‘symbol’ for what we are calling here which is ‘name’.

Because of the nature of Ruby where we able to pass a message and not method call, respond_to which is a rspec matcher check if the object response to a certain message.

 
movie_rspec.rb
it "has a name" do
	Movie.new.should respond_to :name
end

Now lets run our spec which it will fail:

 
» rspec --color
.F
Failures:
	1) Movie has a name
 		Failure/Error: Movie.new.should respond_to :name
   		expected #<Movie:0x007ffe942b9720> to respond to :name

This is error shows we have an expectation error and not a run time error. What the error says is, it expected to respond to :name but it fails. Which means the new Movie object doesn’t not have a property/attribute of :name

To fix that we should declare :name as an attribute of Movie

class Movie
	attr_accessor :name
end

Lets make sure our code works by running our spec:

rspec --color

and yappy we passed out first test, next.

2- Movie has a list of casts

We are testing if the Movie object has a ‘list’ of casts.

We can use the same matcher respond_to but to be more accurate we are testing if it has a ‘list’. As we know Array contain a collection of items which is kind of a list. So our spec goes like this:

it "has a list of casts" do
	Movie.new.casts.should be_kind_of Array
end

We are saying that Casts which are we testing against should be kind of an array. This would fail because we introduced a new method without defending it. Run the test and see for your self.

» rspec --color
.F
Failures:
  1) Movie has a list of casts
     Failure/Error: Movie.new.casts.should be_kind_of Array
     NoMethodError:
       undefined method `casts' for #<Movie:0x007fcd2ba52c88>

To fix this we should add Casts to Movie object attributes, like so:

	class Movie
		attr_accessor :name, :casts
	end

Here we added the new attribute casts, which is supposed to be an Array as we specified in the spec. Therefor this spec would fail.

Failures:

1) Movie has a list of casts
   Failure/Error: Movie.new.casts.should be_kind_of Array
     expected nil to be a kind of Array

The error message is clear. It expected a nil to be kind of Array. Which means it expected the new attribute ‘casts’ to be Array but it is not. We need to return an Array, we should fix this.

We would create new constructor with our variables name and casts.

def initialize(name, casts)
	@name = name
	@casts = casts
end

Doing that only would not solve our problem, because our ‘casts’ is not defined as an Array. We have 2 ways to do so:

1- First option. Declare our variable casts as an empty Array to the constructor if nothing passed, casts= []

def initialize(name, casts =[] )
	@name = name
	@casts = casts
end

This would solve our current spec because we are not passing any parameter to ‘casts’, but this would cause a new error.

1
2
3
4
5
6
7
8
9
10
11
Failures:

1) Movie has a name
   Failure/Error: Movie.new.should respond_to :name
   ArgumentError:
     wrong number of arguments (0 for 1..2)

2) Movie has a list of casts
   Failure/Error: Movie.new.casts.should be_kind_of Array
   ArgumentError:
     wrong number of arguments (0 for 1..2)

This failed because we passed two parameter to the constructor but we didn’t update our spec. So we should do that:

1
2
3
4
5
6
7
it "has a name" do
	Movie.new("Some Name").should respond_to :name
end

it "has a list of casts" do
	Movie.new("Some Name").casts.should be_kind_of Array
end

Now our specs are passed, Hurray!

2- Second option, declare our list of casts as an Array when we pass it. Our goal here is not be able to create the Movie if we are passing a list of funny casts names.

We would use ‘context’ with our spec, which is short version if you would say of describe. We would create a variable for funny names using let() method which would pass a block with expression assigned to the funny name variable.

context "given a funny list/array of casts" do
let(:funny_casts) 
	it "fails to create given a funny cast list" do
		expect {Movie.new("Some name", funny_casts)}.to raise_error
	end
end

As you would guess, we expect to see an error when we pass a funny cast name.

Failures:

1) Movie given a funny list/array of casts fails to create given a funny cast list
   Failure/Error: expect {Movie.new("Some name", funny_casts)}.to raise_error
     expected Exception but nothing was raised

Lets write code to pass our spec. We would raise an Exception unless Casts is an Array.

	def initialize(name, casts = [])
		raise Exception unless casts.is_a? Array
		.
		.
		.
	end

3- Complains when Movie name has a bad word

Our goal is to raise an error if the Movie name include a bad name in it.

movie_rspec.rb
it "complains if there is a bad word in the name" do
	expect {Movie.new("Ugly Name")}.to raise_error
end

To make sure it fails first we run the test, and it does. So lets fix that.

movie.rb
def initialize(name, casts = [])
	.
	@name = name
	@casts = casts
	raise Exception if @name && has_bad_name?
	.
	.
	.
end

Our spec would fails because it doesn’t know about our new method `has_bad_name?’ So we have to create that method which it will include list of words that are bad.

With our new method had_bad_name? we want to show an error if list of bad words such as ‘ugly’ includes downcase or uppercase @name.

def has_bad_name?
	list_of_words = %w{ugly bad lousy}
	list_of_words.include? @name.downcase
end

When we run our test it would fails because list_of_words it contains all specified words as one {"crappy bad lousy"} instead of each one by it self {"crappy", "bad", "lousy"}. to fix that, we would use split method and make sure the final list of words is been subtracted from the Movie name that include bad name.

Run our test and it would pass. Yeaaay we are one test away from finishing our specs.

4- Favour cast name when it is a celebrity

We want to favour a cast name when it is a celebrity.

it "is favoured of it has a celebrity in it" do
	Movie.new("Some name", ["Matt Damon", "Someone"]).should be_favoured
end

Out test would fail because it doesn’t know ‘be_favoured’ method. We are saying here that Movie should be favoured if it has a celebrity ‘Matt Damon’. But rspec doesn’t have be_favoured method. When this happens ‘missing method’ comes to work. It checks if the subject of the spec has a predicate matcher or a method with last part of it match our favoured method. So let’s check if the favoured method return true for ‘Matt Demon’ like so:

1
2
3
4
5
6
7
8
9
10
def favoured?
	@casts.include? "Matt Damon"
end

Run our last test and it would pass.
» rspec --color
	.....

	Finished in 0.00796 seconds
	5 examples, 0 failures

Yeaaay we have done it. We have covered a lot of aspects with Rspec. Lets recap:

####1- respond_to matcher We use it when we want to check if our subject response to certain message subject.should respond_to :message

####2- be_kind_of matcher We use it when we want to check if our subject belongs to an Object, like inheritance. subject.should be_kind_of Object

####3- be_predicate matcher We use it when we want to check if our subject has a method that returns true or false. Using missing method feature in rspec this allows us to identify boolean method. subject.should be_predicate and def predicate?; end

####4- Exception We use it when we expect an exception to be raised
expect {block}.to raise_error

Here are the final rspec file and our Movie class:

###A- movie_rspec.rb Movie RSpec:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
describe Movie do
	it "has a name" do
		Movie.new("Some Name").should respond_to :name
	end
	it "has a list of casts" do
	Movie.new("Some Name").casts.should be_kind_of Array
	end
	context "given a bad list/array of casts" do
		let(:funny_casts) 
		it "fails to create given a bad player list" do
			expect {Movie.new("Some name", funny_casts)}.to raise_error
		end
	end
	it "complains if there is a bad word in the name" do
		expect {Movie.new("ugly Name")}.to raise_error
	end
	it "is favored of it has a celebrity in it" do
		Movie.new("Some name", ["Matt Damon", "Someone"]).should be_favored
	end
end

###B- movie.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Movie
	attr_accessor :name, :casts
	def initialize(name, casts = [])
		raise Exception unless casts.is_a? Array
		@name = name
		@casts = casts
		raise Exception if @name && has_bad_name?
	end
	def has_bad_name?
		list_of_words = %w{ugly bad lousy}
		list_of_words - @name.downcase.split(" ") != list_of_words
	end
	def favored?
		@casts.include? "Matt Damon"
	end
end

Rspec is fun to use therefor; Happy Coding, eh! ;)