html objectification with the dom

Take a look at this awesome website for the City of New York:

Screen Shot 2014-03-25 at 11.06.22 PM

There’s so much we can do!  Click on the arrows at the left and right to see other top headlines!  Click on “Select Language” and see a list of all the languages available for translating the page!  Hover over “NYC Resources” or “311″ or “Office of the Mayor” or any of the other links across the navigation bar, and watch their background color change from white to black (and text color from black to white)!

But the main HTML for the website, which defines the elements on the page, and the CSS, which defines the styling for those elements, are merely more than text files when they are sent to the web browser.  The browser is also sent a separate file in Javascript (or a similar dynamic language) which defines the dynamic behavior for the page.    However, with the HTML in its native form–as a hypertext file–the Javascript file has a very limited ability to be able to interpret the HTML and know which method should be done on which part of the page.

So how do the HTML and Javascript communicate?

The answer lies in the Document Object Model, or DOM.  When the web browser receives the website it requested from the server, it takes the lowly HTML file and converts each element into an object, which holds the attributes and values of that element as key-value pairs, and also holds information like the parent of the element (was it nested within another HTML element?) and its position among its “siblings” (is it the second element of a bulleted list? the fifth?).

The browser stores the DOM and then is able to understand Javascript methods that reference particular elements.

dom

Image source: webstepbook.com

The example above shows how we would change the image that is displayed as “icon01” on the page. The HTML file, when stored in the DOM, can be referenced with the name “document”.   The built-in function getElementById is called on document, and the id “icon01″, which uniquely refers to the octopus image, is passed in.  The result, which is a DOM element object, is saved with the variable name “icon”.  Then, the “src” property of that object is set to the new image “kitty.gif”, replacing the octopus picture with a kitty picture.  When exactly this change would occur (when the user clicks on a specific place on the page, or immediately after the page loads, or 5 seconds after the page loads) would be dependent on which Javascript function we call on that element (which is not shown in the example).

With the DOM in place, the HTML and Javascript are able to work together to produce a happier and more dynamic website.

 

Advertisements

method mail: calling “send” in ruby

Objects in Ruby like to get mail via the send method.  But they only like to get mail if there are exactly two things in the parameters envelope: a method that can be called on themselves, and any arguments needed to complete that method call.

Here’s a simple example:

1Here, we are calling .send on 1.  That makes 1 the receiver of this mail.  1’s really excited to be receiving mail!  However, as we established, he only likes to receive mail that contains a method that can be called on him, along with the corresponding additional argument(s) for that method.  Since he’s an integer, he can receive any method defined for the Integer class (read more about these methods over at the Ruby documentation).  We also note that the method which is sent can be expressed as a string or a symbol .  (Again, refer to the Ruby documentation to verify this.)  This will come in very handy in our next example.

Sending “+” 2 to 1  is a pretty simple example, and one for which we can be just as efficient without using .send.  One place where the amazing Rubyesque power of .send can be seen when we want to call a class’s instance method multiple times with different arguments without being overly repetitive.

Consider the scenario of setting values of instance variables for a class.  Here, the attribute accessor method for each variable is called in order to set it to a given value.

2

We would like to create an instance of the class called yc and set its instance variables to the variables in the hash yc_attr.

3Our first thought may be to manually go through and write five statements, one for the assignment of each instance variable.
4This is pretty verbose.  Wouldn’t it be great if we could just iterate through each of the attributes, setting the class instance variable whose name matches the hash’s key equal to value at that hash key?  Here’s the idea of what we want to do:5

This won’t work, because when we say yc.key the object yc is looks for a method called key, rather than replacing the value of the variable that has been assigned to key.

This is where send comes to the rescue!  We can do this, thanks to send‘s ability to correctly interpret a method name that is passed in as a string.

6

Mass assignment in this way can also come in handy in Sinatra and Rails, when you need to create a form field for every key in the params hash or do other mass assignments from the params hash to an object.

instantiating puppies: class methods vs. instance methods in ruby

When I was looking through examples of classes written in Ruby, I noticed that some began with self., while others did not.  What is the difference between these self. methods and non-self. methods?  (are the latter less selfish? less self-involved?)  When I’m writing my own classes, how do I know if I’m supposed to put self. in front of it?

It turns out the difference between these types of methods defined within a class is that any method that begins with self. is a class method, while any method that does not begin with self. is an instance method.

Awesome. But how do instance and class methods work?

When you define a class, you’re defining a set of rules for objects that all have the same descriptive qualities and behave the same way.

Say, for example, you want to talk about puppies.  All puppies can wag their tails and gaze at you longingly with sad puppy dog eyes.  There are instance methods–they refer to what a puppy, one instance of the Puppy class, can do.  These methods do not begin with self.

1
Say we want to create a few different puppies–a few instances of the Puppy class.  We can keep track of all of the puppies that have been created by saving each puppy (each instance of the Puppy class) into an array.  We’ll add in a line in the initialize method to add the puppy that’s currently being created into an @@puppies array.

2
This is like putting your puppies in a playpen, where they can all safely play together.   Let’s make it an array-shaped playpen to represent the @@puppies array.

photo 1
Let’s put three puppies in our playpen.  As each puppy is instantiated, the initalize method adds it to the @@puppies array.

3
Now when we look at our playpen, we see all of the puppies happily frolicking together.
photo 2

What if we wanted to find out things about the collection of puppies we have?

This is where class methods, the ones that start with self, come in to play.   Here is the Puppy class, updated to include some class methods:

4
 self.count tells us how many puppies we have in the playpen. self.all returns the array of each of the puppy instances.  And self.find_by_name, with a puppy name passed in, returns the puppy with that name. 

So now we’ve seen that instance methods act on an instance of a class (a single puppy), while class methods act on the class itself (the playpen of puppies).

ruby != python

I began my study of Ruby with a background of mostly Python.  Since Python and Ruby are both very high-level languages, when I encountered a concept I hadn’t yet learned to implement in Ruby I would default to a Ruby-ized version of the Python implementation.

This is a serious offence to Ruby, the most eloquent of all modern programming languages.  Powerful as it may be, Python is really just a tab-delineated heap of old cardboard and soda cans, while Ruby is designed for beauty and elegance and should probably be on display at the Museum of Modern Art.

rubymoma

Ruby exhibit at MoMA

Not realizing Ruby has several versatile methods for finding elements during the iteration process that fit a certain case, I tried to modify my favorite Python technique for iteration in a simple Ruby method.  The method’s objective is to return the smallest integer between 1 and 10 for which the square of the integer is greater than 30.  If no integer is found that is greater than 30 when squared, the method returns false.

In Python, the method can be implemented as follows:

Screen Shot 2014-02-12 at 9.24.03 PM

The return value of this method is 6, as expected.

Now I coded up this method in Ruby a sad, pathetic, Python-esque way:

updated

This yields false, which we know isn’t correct!

It turns out that in Ruby, the break keyword breaks out of the current loop but not the method entirely:

The Ruby documentation for break!

The Ruby documentation for break!

Therefore, this method will iterate through the integers, and when i = 6 it will find that the if condition is satisfied.  It will break out of the loop and move to the first line of code below the loop, which is false. Since this is also the last line of code before the final end keyword in the method, Ruby will implicitly take it to be the return value of the entire method.

We’ve seen that if you lift a built-in method name or keyword from one language and use it in your program in another language, even if you have no runtime errors the program won’t necessarily behave the way you expect it to.  Coding a method in Ruby and assuming it to behave like Python is a little like stepping into the cockpit of an airplane expecting it to drive like a car. (although if you had to do one of the two, coding blind is probably better than flying blind.)  Always make sure to read up on the behavior of the tools you have before taking off on your programming journey.