WTF is up with the Rails asset pipeline

In my last two group projects my world has been turned upside down with the pain that we like to call the rails asset pipeline.

On the surface level any rails projects ships with its own standard folders and directories which keep all your files. We call these files “assets”.

In a rails project is very likely that you will have code that you write and then code and libraries that you use from other people, either open source or commercial. Our main problem that we faced in the asset pipeline was integrating other people’s code into our app.

Libraries that you use from the internet (which you do not write yourself) are usually stored in your vendors folder. These will include any external javascript, html and stylesheet files that help you to create your app.

For my two projects on our localhost the app worked fine (for the most part) but whenever we deployed to Heroku there were all kinds of problems. It took hours to figure out and the problems were 97% of the time caused by the rails asset pipeline.

In my endless troubleshooting of rails asset pipeline issues on Heroku, one thing was etched into my brain:

When Heroku compiles your assets it compiles all of your asset files into ONE FILE

E.g. if you have 10 different javascript files, Heroku will gather and append them into each other to create one file. And if you have an error in a single one of those files it will cause the whole compiled file to break.

This will save you some time when you’re just starting out. Remember to use the console and go through each and every javascript error line by line to figure out a solution. Unlike localhost, Heroku is less forgiving about javascript errors and you will need to fix them before the apps runs correctly.

On an unrelated note here is a little app I made called Words With Jaden, inspired by:

  • Momentum Chrome extension
  • Jaden Smith
  • My group talking bad about my 80s pop/rock knowledge 😀
Advertisements

Using google maps to build a flight log

DEMO HERE

Airplanes and the idea of flight fascinated me as a young boy. I remember the anticipation of traveling to far away places with my family and could not wait to sit down in my blastoff seat and buckle up.

One of my favourite things to do on the airplane was to check the flight log application on the tv in front of me. My brother would watch movies and I was the weird kid constantly clicking the screen to show the temperature, altitude and flight path along the journey. The movement changed very little minute by minute but sitting there watching the small airplane move was enough entertainment for me.

Last night I set out to make my own flight log visualization app using the google maps api.

Customizing your google map object

The google maps api is well documented and gives you very clear code examples to get up and running with a working map. I used a snazzy maps skin to change the look of the map. It allows you to create an array of google maps styling and then use those styles to initialize your google map:


var styles = [  
      {
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [
                {
                    "color": "#004358"
                }
            ]
        },
        .......etc
    ];

var styledMap = new google.maps.StyledMapType(styles,  
      {name: "Styled Map"});

    // Create a map object, and include the MapTypeId to add
    // to the map type control.
    var mapOptions = {
      center: new google.maps.LatLng(32.3078, -64.7505),
      zoom: 5,
      mapTypeControlOptions: {
        mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'map_style']
      }
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

    //Associate the styled map with the MapTypeId and set it to display.
    map.mapTypes.set('map_style', styledMap);
    map.setMapTypeId('map_style');

Once you have the array of styles you can use that to create a styled google maps object. Next you can just to display that maps object on your index.html page.

Gathering location data for your coordinates

After you have a working map on your index.html page, the next step is to gather the starting location and destination from a user and retrieve the relevant latitude and longitudes based on those locations.

$('button').click(function(){
var from = $('#from').val();  
var to = $('#to').val();

var url_from = "https://maps.googleapis.com/maps/api/geocode/json?address="+from+"&key=AIzaSyAIAT5ptZVJqiFiTQZxAXp6KT8jREfKidU";

var url_to = "https://maps.googleapis.com/maps/api/geocode/json?address="+to+"&key=AIzaSyAIAT5ptZVJqiFiTQZxAXp6KT8jREfKidU";

....
)};

You can use jQuery to grab the locations from the user input boxes. Remember to include your jquery/js files before your custom javascript ones so it loads on the page first.

Once you have the location you then need to create a url to pass through the google maps API in order to retrieve the relevant location JSON data. Google is smart and uses advanced geocoding to map a location “word” to it’s relevant latitude and longitude.

This is helpful when drawing out the flight log between two points because it needs a latitude/longitude. For example a “New York” to “Paris” query string must map to the relevant (44.9999,33.4444), (23.000,67.3388) locations:

$.getJSON(url_from,function(data){
            from_loc.push(data["results"][0]["geometry"]["location"]["lat"]);
            from_loc.push(data["results"][0]["geometry"]["location"]["lng"]);
        })

        $.getJSON(url_to,function(data){
            to_loc.push(data["results"][0]["geometry"]["location"]["lat"]);
            to_loc.push(data["results"][0]["geometry"]["location"]["lng"]);
        })

        var lineCoordinates = [
          new google.maps.LatLng(from_loc[0],from_loc[1]),
          new google.maps.LatLng(to_loc[0],to_loc[1])
        ];

       var lineCoordinates = [
            new google.maps.LatLng(from_loc[0],from_loc[1]),
            new google.maps.LatLng(to_loc[0],to_loc[1])
        ];

You can use a jQuery.getJSON(); AJAX request to retrieve the lat-lng from google based on their geocoded locality. That request responds with a JSON of relevant map information based on the location parameter that you passed in.

Drawing the Polyline between two points

The final step is to draw a Polyline and use a generated Polygon to generate the path between the two locations.

var lineSymbol = {  
          path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
          scale: 8,
          strokeColor: '#fd7400'
        };



        // Create the polyline and add the symbol to it via the 'icons' property.
        line = new google.maps.Polyline({
          path: lineCoordinates,
          icons: [{
            icon: lineSymbol,
            offset: '100%'
          }],
          map: map
        });

        animateCircle();

    });
}

// // Use the DOM setInterval() function to change the offset of the symbol
// // at fixed intervals.
function animateCircle() {  
    var count = 0;
    window.setInterval(function() {
      count = (count + 1) % 200;

      var icons = line.get('icons');
      icons[0].offset = (count / 2) + '%';
      line.set('icons', icons);
  }, 20);
}

google.maps.event.addDomListener(window, 'load', initialize);  

The Polyline function creates a line between two points on the google maps path. You can adjust the size, shape and color of the path in the lineSymbol variable. Using the lineSymbol variable you can create the actual Polyline using Google’s built in “new google.maps.Polyline()” function passing in your lineSymbol variagtions and lineCoordinates between the two points.

Finally you have to call the animateCircle() function to actually create the Polyline and display it on the page. And voila you have your first functioning flight log simulator!

Future enhancements

I ran into a few issues while creating this app. The first and most frustrating one was trying to generate a Polygon plane object instead of the default forward facing arrow. The below code is what displays the moving arrow:

path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW

Google uses SVG objects exclusively for their map symbols. The problem here is that you are only limited to a few default SVG symbols. An SVG is a vector based image format for 2D graphics. It is possible to create your own SVGs and after countless attempts I was not able to get it working while drawing the image. For some reason the google maps object was not recognizing my SVG symbol.

I would also love to add some curvature to the flight path. Right now the Polyline draws a direct line path between the two location points. Although visually appealing it is not scientifically accurate. The next step would be to figure out how to add a curved path between the two location points.

The google maps api is a lot of fun to work with. The API docs are super helpful and you can get up and running in a matter of minutes.

Have fun!

What every ruby developer should know before learning javascript

How to transition from Ruby to Javascript in one day

After inundating myself with Ruby for close to six consecutive weeks it was time for us to go on a break. We had a lot of fun together and we learned a lot about each other but evidently in the end, we needed a break to really figure some things out.

Enter JavaScript.

JavaScript is a programming language created in 1995 by Brendan Eich while working at Netscape. Over the last 20 years it has become synonymous with front-end web development which makes it a very important language to know.

This week was our introduction to JavaScript. With my past experience learning Ruby it was an interesting experience diving into a new language. I knew that the syntax would be similar but there are certain design patterns that change from language to language.

It is human nature to want to compare one thing to another. That has been our process through years of evolution. We make patterns and connections in our mind from past experiences which helps us to make sense of the world. The process of connecting those dots happens with people as well as new languages.

The natural tendency for most people would be to compare Ruby with JavaScript and first look for their similarities. This can be a good starting point to familiarize yourself with a new programming language. You understand syntax in one language and expect it to work the same way in another.

However the beauty of something new lies within it’s differences! The magic of learning something that you never knew before is undoubtedly the patterns that are fresh, that are brand new.

Today i want to share some of those with you:

Variable setting

At a fundamental level you need to know how to declare a variable in JavaScript. You can declare a variable in javascript using the var keyword.

var myName = "Sade Adu"  
return "Hi, My name is " + myName

myName = "Daft Punk"  
return "Hi, My name is " + myName  

In JavaScript you can declare a variable by setting var variableName = “Something”. You MUST remember to include var in your declaration or you will run into some severe problems. After declaring the variable with var you can assign it to a new value without including the varkeyword. Additionally JavaScript does not support string interpolation, therefore remember to use the + operator to string values together.

Also, the JavaScript convention for naming variables is to use camelCase!

Declaring a function

Every function in JavaScript is an object. It is one of the design patterns which makes it an object-oriented language. JavaScript functions also make it a very powerful language to do a lot of complex functionalities on the web. Here are 3(+1) ways you can write a function in javascript:

1. Function constructor

var sum = new Function('a','b', 'return a + b;');  
alert(sum(20, 30)); //alerts 50

var Artist = function(name, details){  
     this.name = name;
     this.details = details;
}

return new Artist("Sade", "Goddess")

EQUIVALENT

function Artist(name, details){  
     this.name = name;
     this.details = details;
}

return new Artist("Daft Punk", "Robots")

2. Function declaration

function sum(a, b)  
{
    return a + b;
}
alert(sum(50, 50)); //Alerts 100;


3. Function Expression

var sum = function(a, b) { return a + b; }

alert(sum(10, 10)); // alerts 20


4. Anonymous Function

(function() {
    alert('I am anonymous');
})();

A function in JavaScript is a unique design pattern that will be a little tricky to wrap your head around coming from Ruby. It can act as a sort of class, or a method or even just a block.

In the first example you can use a Function constructor which sort of acts like a class in Ruby. With a Function constructor you can attach methods to the function and create instances of the constructor, similar to an instance object in ruby.

In the second example you can use a Function declaration which allows you to pass that function around to other areas of your program.

In the third example you can declare a function using a Function expression which will be local to the environment that you are working in. A function expression can be useful when you only need to use a function object in one area of your program and you want it to stay local to that scope.

The last example is an anonymous function which is extrememly popular in JavaScript. An anonymous function is a function that does not have any stored identifier attached to it. As you can see in the example we do not declare a Function name or pass in any arguments. The anonymous function is useful because it is not accessible after it’s creation which allows you to use it as a private function.

Methods

A javascript method is a function associated to an object.

function artist(name, details) {  
    this.name = name;  
    this.details = details;
    this.changeName = function (name) {
        this.name = name;
    }
}

In the above example we use a method changeName which will allow you to change the name of your object.

No arrity checking

JavaScript uses a concept of no arrity checking which means that it does not keep track of the arguments you pass in.

function showArgs() {  
   return arguments
}

new showArgs([1,2,3,4,5])  
=>/ 1,2,3,4,5 

It’s important to note here that arguments is not an array, but rather an array-like object. There are certain methods you can use on arguments which behave like an array and others you cannot.

Prototyping

Prototyping is a feature of JavaScript that allows us to create instance methods on an object.

Artist.prototype.whisper = function() {  
  return "Hi my name is  "+ this.name + " and I am a " + this.detail;
}

Using a prototype allows us to add new properties and methods to the Artist object. Whether you are creating a prototype property or method, the really useful feature is that it is available to all of the objects when you attach it.

Hoisting

JavaScript has a very magical concept of hoisting which allows you to use a variable before it has been declared.

Example 1

x = "Sade"; // Assign "Sade" to x  
var x; // Declare the variable x  
x =// is now "Sade"

Example 2

var x; // Declare x  
x = "Sade"; // Assign "Sade" to x   

Example 1 and 2 will return the same result for x. With JavaScript hoisting, the default behaviour is to push all declarations to the top of the current scope (script, page or function). In a nutshell at run-time JavaScript moves all of your declarations to the top of the file and then runs the file.

Hoisting makes writing code very forgiving to the careless programmer. To avoid any unwanted bugs or errors it is still a good practice to declare your variables at the top! Key point to remember when hoisting:
JavaScript only hoists declarations, not initializations.

E.g. Example 1 does not give the same result as Example 2:

Example 1

(function() { 
  var a = 'Sade'; 
  var b = 'Daft PUnk'; 
  // more lines of code 
})(); //undefined

In this example a and b are undefined when the program runs.

The reason is because the declaration (var a), not the initialization (=”Sade”) is hoisted to the top.

In JavaScript hoisting a is declared before it is used and since initializations are not hoisted, the value of a is actually undefined.

Example 1 is the same as writing:

What's really happening:

(function() { 
  var a, b; // variables declared 
  a = 'Sade';   //initialization
  b = 'Daft Punk'; // initialized 
})();  //undefined 

So remember that in hoisting ONLY the declarations get hoisted to the top, not the expressions or initializations. Declarations = pushed, not anything else.

In our next installment we will talk about IIFE, closures and *this!

 

recursion, recursion, recursion

Okay I learned one of the coolest ruby techniques that I’ve seen thus far, it’s called recursion and it’s awesome.

Recursion allows you to define a function(method) then call itself within the body of that function. On first glance it looks very confusing but basically you are using the function within the function itself. Even trying to explain it here is very tough. Let’s try an example.

def countdown(n)  
  if n == 0
    puts "Blastoff!"
  else
    puts n
    countdown(n-1)
  end
end

In this program called countdown we take a number “n” and pass it through the code block. The final result is a countdown of numbers until you get to 1 and then it prints out “Blastoff!”. You could also write this program using a while loop:

while n > 0  
puts n  
n = n -1  
end  
puts “Blastoff!”  

but with recursion we can save time and energy by calling the function on itself. Using recursion we can write less code and make our program look cleaner. For instance let’s say we have countdown(10). Following the path in the code block we check if n is equal to 0. Since it’s not we move on to the else portion of the code block. We puts n and then find countdown(n-1) which is the same as countdown(9). At this point we have to go through the steps again using “n-1″. Ok let’s check if “n-1″ is equal to 0. 9 does not equal 0 so we go to the else portion of the code block, puts 9 and then run through countdown(9-1) or countdown(8). The program runs through this system until countdown(1) where countdown(n-1) would equal 0 and the program can end.

This was not a very thorough explanation I know. I’m still wrapping my head around it myself but I wanted to type it out to understand it better. I’ll have a more structured answer for you in a bit!

Simple things

def englishNumber number  
  left = number
  write = left/100              # How many hundreds left to write out?
  left = left - write*100       # Subtract off those hundreds.

  if write > 0
    return 'one hundred'
  end

  write = left/10               # How many tens left to write out
  left = left - write*10        # Subtract off those tens.
end

puts englishNumber( 32)  
puts englishNumber(100)  

The above code snippet is part of a program that turns an integer into it’s english version. E.g. if the number “1” passes through the program it will return “one”.

The whole program is relatively simple and pretty straightforward but I wanted to talk about it because it exposes one of the most interesting things I’ve found in programming. Simplicity is the gift and curse of programming.

For the last hour I’ve written out this program then manually went through each step to find out what’s really happening. With pen to paper I’ve drawn out each sequence, following along as the program moves from line to line. I’ve spent the last hour trying to figure out what happens in the above section.

I knew that it was an easy solution but I couldn’t quite figure it out. At the end I realized that I was returning the float instead of the integer in the “write” section. It makes a difference using “32 – 32″ as opposed to “32 – 30″.

These are the biggest mistakes I make when writing code. It’s the simple things that sometimes trip me up. Whether it’s missing out an apostrophe for quotation marks or not writing out the full variable name, I always find small errors when I go over my code.

I have a high attention to detail but with programming you must take that to another level. It’s a gift and a curse because code allows you to solve complex problems with relatively simple structures, algorithms and programs. On the other side it can also be a curse because you can make simple mistakes if you’re not thoroughly attentive to detail.

This also boils over to real life. The biggest problems we have our usually related to the simpler things. Overweight? You probably are eating the wrong foods at the wrong time. Tired? You might not be getting enough sunlight or exercise.

Of course most of the time there are a lot of other external factors which also contribute to these problems. However, the best steps to solving them are most effective when addressing the basic issues first.

Let’s make sure to take care of the simple things.

Stop what you’re doing and start using ruby’s inject method

The Ruby inject method has a few different use cases. For me personally I’m really starting to love summing numbers with the method. It’s still a little confusing for me but I think I’m finally starting to get the hang of it.

Let’s take a look at an example.

Say we have an array of numbers that we want to sum:
[ 5, 6, 7, 8 ]

We could use a loop to sum the numbers:
sum = 0
[5,6,7,8].each { |x| sum += x }
sum

With the inject method, we can sum the numbers on one line:
[5,6,7,8].inject(0) { |x,y| x+y }

The inject method takes an argument and a block. In this example we set the argument as “0” and the block is “|x,y| x+y”. When we call the inject method, the argument gets set as the first parameter of the block. In our case “x” would initialize to “0”. [If there is no argument then inject just takes the first element of the array as the first parameter “x”. ] Next inject takes the second parameter “y” as the first element in our array which is “5”. So now in our block we have “|0,5| 0 + 5″. This block evaluates to the integer 5 and inject stores that as “x” for the next iteration. In the next iteration we have “|5,6| 5+6″. Enumerable#inject iterates through each element of the array and sets the value of the block to the first parameter “x”. That is how it sums up all of the integers in the array.

It’s a very useful tool and can be used in a variety of instances. Using inject we save time and space by writing less code. I’ll be trying to use inject more often, especially when I have to sum certain values. I’ll get a deeper understanding of it when I use it more.

Intro to Mandarin (Pinyin)

Xiansheng (Mr., husband, teacher)
Ni hao (how do you do/ hello)
Xiaojie (miss/ young lady)
Qing (please)
Wen (to ask)
Nin (you-polite)
Gui xing (what is your honorable surname?)
Wo (I)
Ne
Jiao (to be called; to call)
Shenme (what)
Mingzi (name)
Wang Peng
Li You
Shi (to be)
Laoshi (teacher)
Ma
Bu (not; no)
Xuesheng (Student)
Ye (too; also)
Zhongguoren (chinese people)
Meiguoren (american people)
Pengyou (Friend)
Taitai (wife/Mrs.)
Na (that)
Zhang (measure word for flat object)
Zhaopian (picture; photo)
De (‘s)
Zhe (this)
Baba (Father)
Mama (mother)
Zhe ge (this)
Nanhaizi (boy)
Shei (who)
Ta (he)
Ta (she)
Didi (younger brother)
Nuhaizi (girl)
Meimei (younger sister)
Nu’er (daughter)
You (to have)
Erzi (son)
Mei (not)
Xiao (small; little)
Gao (tall)
Jia (family)
Ji (how many)
Gege (older brother)
Liang (two; couple of)
Jiejie (older sister)
He (and)
Zuo (to do)
Yingwen (english language)
Lushi (lawyer)
Dou (both; all)
Daxuesheng (college student)
Yisheng (doctor)
Yue (month)
Hao (#)
Xingqi (Week)
Tian (day)
Shengri (birthday)
Jinnian (this year)
Duo da (how old)
Sui (year of age)
Qing (to treat someone)
Chi (to eat)
Wanfan (dinner)
Chi fan (to eat meal)
Zenmeyang (is it ok)
Tai…le (too; extremely)
Xiexie (thank you)
Xihuan (to like)
Haishi (or)
Keshi (but)
Hao (ok)
Women (we)
Dianzhong (o’clock)
Ban (half)
Wanshang (evening)
Zaijian (see you again)
Xianzai (now)
Ke (15 min)
Shi (matter/affair/business)
Mingtian (tomorrow)
Mang (busy)
Jintian (today)
Hen (very)
Weishenme (why)