Traversing the Internets

Web Development in NYC

Flatiron School Day Twenty Four - Include or Extend for a Module?

| Comments

Yesterday I found myself writing my first module. For those who don’t know, in ruby a module is a package of methods that you write and store in a seperate place, which you can call on inside a class to include the methods contained within. These are used when you want to have the exact same methods included in multiple places, using a module is cleaner and DRY’er than repeating the method definitions in every class.

There are two ways to add a module to a class, include and extend. The include keyword will bring the module methods into the class as instance methods, allowing instances of the class to use the methods. The extend keyword will bring the module methods into the class as class methods, allowing the class itself to call those methods.

It’s important to understand which of these two are appropriate to use on the module and to design and structure your module so that it can be used correctly. If you use the wrong keyword to bring the module into a class you will not end up with the expected functionality. Additionally, modules should be designed and structured with this in mind, separating methods that are intended to be instance methods from those that are intended to be class methods.

Flatiron School Day Twenty Three - RSpec Musings

| Comments

Todays post is going to be short. I’m going to write down some thoughts about RSpec and writing tests.

Write out what you want your tests to do without worrying about the actual syntax for the tests first. Statements like “it ‘should do whatever this test should do’” do can be followed with pending on the next line. This allows you to write out all of the ideas with what you would like your code to do without having to worry about any syntax yet. You can then impliment tests as you’re comfortable and write the corresponding code to pass them when the tests are ready.

Sometimes it’s helpful to write out skeleton tests, to describe what features a given unit of work should DEFINITELY have without worrying too much about potential features or tasks that it may need further down the line. Once you get the basics built out on your files when you come across new functionality that is needed you can go back and add tests and then add the code to get those to pass. This approach can save some time as you won’t need to try and brainstorm every feature you might come across and can instead focus on making sure your tests are good and that your code passes them. You can always add more tests later

With the level of complexity of our current projects, writing tests often feels very frustrating. It feels like spending a lot of time writing out very basic things about the code when we could be actually writing the program. Intellectually I’m aware that this work will pay off down the line as projects become more complex, so in the meantime I need to keep reminding myself that it’s not slowing us down, it’s preparing us for things to come.

Flatiron School Day Twenty-Two - SQL Bits

| Comments

I started working on a mini-project yesterday bto reinforce the different topics we’re covering in Flatiron. While it’s not done-enough to go over in detail yet I wanted to cover a few bits of SQL that I found particularly useful in getting the program to its current state.

The SQL side of the program exists to keep a unique record of articles off of Hacker News that meet certain criteria. The scrape can be run multiple times over multiple days, weeks, etc. so it was important that the SQL side of the program not continuously re-enter the same article over multiple scrapes. Here’s what the code looks like…

database.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
class Database

  @@db = SQLite3::Database.new('articles.db')
  @@db.execute("CREATE TABLE if NOT EXISTS articles(id INTEGER PRIMARY KEY ASC, title TEXT UNIQUE, url TEXT, parent_url TEXT, points INTEGER);")

  def self.insert(array)
    array.each do |article|
      sql = "REPLACE INTO articles(title, url, parent_url, points) VALUES (?,?,?,?)"
      @@db.execute(sql, article.title, article.url, article.parent_url, article.points)
    end
  end

end

There are a few bits of this code I would like to highlight.

“CREATE TABLE if NOT EXISTS” – This one should be familiar to most Flatiron students already, but since some of our projects and examples have assumed the existance of a table I thought it would be worth mentioning. The ‘if NOT EXISTS’ part is important to make sure that you are not creating a new table every time the code runs, this code will only execute the first time the program runs, unless the ‘articles’ table is deleted from the database (this would have to be done manually by the user).

“title TEXT UNIQUE” – This is one that I had to look up what I wanted SQL to do before I could figure out how to do it. This tells the database that while the ‘title’ column is not the primary key, that it is unique and that SQL should raise an error if something attempts to add an item with the same title as something else to the table.

“REPLACE INTO” – The work-horse piece of code, normally we would use ‘INSERT INTO’ but in this case, I chose to use ‘REPLACE’ for two reasons. First, it resolves any conflicting titles by replacing the old entry with the newer one, which makes sure that we only have unique entries in the table. Second since it replaces the old version with the new one, it will update any other data about the article that has changed since the last time the scrape was run (for instance, if the number of points were to change).

These three peices that were previously unfamiliar to me do a lot of work in very little space. Because I don’t need to write methods to check for some of the things these take care of automatically, we save a lot of space and the code is easy to read. Thanks for reading, I hope if you’re working with SQL these little bits are helpful!

Flatiron School Weekend Three - the Tap Method

| Comments

#1 type of tap at the Flatiron School

Today I wanted to talk about a couple ways I think the .tap method in Ruby is useful. The first time a lot of us at Flatiron saw this method, it was used in an RSpec test and threw many of us for a loop trying to figure out exactly what the test was doing. After using the method for a bit, it’s become clearer what the tap method is, a shortcut.

Equivalent Code…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Dog
attr_accessor :name, :favorite_food, :breed
end

# The Three code samples below all are based on the above class.

clifford = Dog.new.tap{|x| x.name = "Clifford"; x.favorite_food = "Children"; x.breed = "Big Red Dog"}

# The code above and below this comment are equivalent.

clifford = Dog.new

clifford.name = "Clifford"; clifford.favorite_food = "Children"; clifford.breed = "Big Red Dog"; clifford

# This code is also equal to the code below, in case semi-colons make you uncomfortable...

clifford = Dog.new
clifford.name = "Clifford"
clifford.favorite_food = "Children"
clifford.breed = "Big Red Dog."
clifford

Those kids should be screaming and jumping off that roller coaster.

So the three pieces of code above all return the same value with different ways of getting there. The tap method offers a few advantages over the others.

First, you get the same return out of a single line of code. This advantage should be obvious from looking at the code (you can paste the samples into IRB to confirm equality)

Second, you don’t need to call the variable to get the return value, which also means…

Third, you don’t have to store the object in a variable at all. This looks like…

The Following Code Samples return the same value.
1
2
3
4
5
6
7
#Original code from above

clifford = Dog.new.tap{|x| x.name = "Clifford"; x.favorite_food = "Children"; x.breed = "Big Red Dog"}

#Same return value without having to store the object in a variable

Dog.new.tap{|x| x.name = "Clifford"; x.favorite_food = "Children"; x.breed = "Big Red Dog"}

This allows you if you are creating a large number of objects and passing them into a larger data structure (hash, database, array) to not have to first store the object in a variable before passing the variable into your data structure, saving steps along the way. With the other ways of making clifford ‘real’, you would need to store the object in a variable to be able to manipulate it after it was made, with .tap you can make clifford exist and have traits without ever having to tell the computer to remember him.

Flatiron School Day Eighteen - Suck It Up, Break Your Code.

| Comments

I was going to write another small technical post today but that is going to have to wait until tomorrow. Today I wanted to remind myself and anybody who reads this about the mental blocks with regard to refactoring your code. Here at Flatiron we follow the (I think Kent Beck) motto of “Make it work, make it right, make it fast.” Sometimes this leads to the first working piece of code being pretty ugly. If you’ve just spent hours in a team working through pitfalls to get the code working, it may be overwhelming to go ahead and start refactoring the code once its running and/or all your tests are green.

The big thing I wanted to focus on is that provided you’re not living in an alternate dimension where there is no Git, you can feel free to burn your working code to the ground and swim in its ashes. You still have that working code in version control, there is nothing intimidating about altering it to where it starts failing tests or stops functioning. Even if you never find a better solution on a given project, you never will if you don’t start smashing your code and trying to rebuild them.

In Office Space they took the printer out into a field after one too many “pc load letter” errors and smashed it to pieces. Unfortunately with hardware, its pretty difficult to put back together. Count yourself lucky that with code that is not the case, you can destroy your project over and over again and roll it back if you aren’t making useful progress.

Get over the fear of the red results and break your code, it’s liberating.

Flatiron School Day Seventeen - Class Methods

| Comments

I wanted to write down a little bit about my understanding of how methods work inside of classes and how to know if you want your method to be ‘self.method’ or just ‘method.’

Take the following situation…

The Dog Class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Dog

  attr_accessor :name, :color, :breed, :number_of_legs

end

fido = Dog.new
fido.name = "Fido"
fido.color = "Red"
fido.breed = "Direwolf"
fido.number_of_legs = 4

other_fido = Dog.new
other_fido.name = "Not Fido"
other_fido.color = "Green"
other_fido.breed = "Regular Wolf"
other_fido.number_of_legs = 3

So we have the class Dog with a few attributes, and we’ve created two dogs. Now we’re going to create two methods, one to make an individual dog bark and one to make the Dog class bark.

I Should Have Named One of the Dogs Charles BARKley.
1
2
3
4
5
6
7
8
9
10
11
class Dog

  def barkley
    puts "I AM TOTALLY BARKING YOU GUYS"
  end

  def self.bark
    puts "THE CONCEPT OF A DOG IS BARKING, RUN FOR YOUR LIVES!"
  end

end

Now, if we put fido.barkley we will see “I AM TOTALLY BARKING YOU GUYS”

If you put fido.bark though, you will get a NoMethodError, because the bark method is defined for the class it was in because we defined it as self.bark, with self referring to the current object its contained within.

So… If we put Dog.bark we will see “THE CONCEPT OF A DOG IS BARKING, RUN FOR YOUR LIVES!”

Similarly, if we were to call Dog.barkley we would again get a NoMethodError because the method is defined without the self demarcation, telling ruby that it is to be used by individual dogs, not by the class as a whole.

So bringing things back around, if you want your overall class to respond to a method, name it as self.method, if you want a specific instance of that class to respond to it, do not have the self in there.

Flatiron School Day Sixteen - the Pareto Principal

| Comments

The Pareto principal is also known as the ‘80/20’ rule. It’s a rule I’ve heard and seen in various academic endeavours and in business as well. Yesterday was the first time I really looked at it with regard to coding. Avi mentioned during the day that 80% of the work on a project comes in the last 20% of the project and that got me thinking about my work and if the principal applies.

It turns out after looking at my ‘to do’ list for Flatiron that the only things I have unfinished stand about 80% done. Some are a little further along, some less; but the overwhelming majority of my unfinished work falls right around ‘almost done.’ It always seems to be that one method I can’t get to function correctly, or the one or two tests I just can’t seem to get to pass that are holding up some of my work from being completed.

So I’ve decided I’m going to stop caring about pace. I’m not going to find it odd or frustrating anymore when I rush through 80% of a project only to find myself stuck in the mud at the end. I’m just going to push through it, knowing that it’s completely normal and not something that’s going to change.

Flatiron School Day Fifteen - Structs

| Comments

Today I’m going to take a break from ‘talking about my day’ and instead try and explain something technical. Today I’m going to talk about structs, a concept in Ruby we haven’t actually learned at Flatiron yet. This article is inspired by the presentation on Speaker Deck by Ken Collins, so thanks Ken for getting me thinking about structs!

I’m going to try and break down structs into three parts. Concept, Code and Uses…

Concept: A struct is a miniture class, created quickly and at its core it is a class that only has basic getter and setter methods.

Code: There are a few ways to create a struct. I think the easiest to do and understand is as follows…

Struct Creation
1
Location = Struct.new(:name, :lattitude, :longitude)

That’s all there is to it, this quickly creates a Struct Class called Location that keeps track of a locations name, lattitude and longitude coordinates. Which brings us to…

Uses: Structs seem like they are best used for set values for things that don’t need to have any class methods. Things like GPS locations seem like a great reason to use a struct instead of another structure. Any time where you know there is a fixed amount of information you need a struct can be a quick and easy way of storing information about those things, I’m going to try and use structs more and see if I can’t find even more useful ways to implement them!

Flatiron School Day Weekend Two

| Comments

Weekend two was a lot of fun. I managed to end up pretty comfortable with SQL pretty early in the day and we moved onto some other new and interesting things later.

Namely Nokogiri, this ruby gem for scraping web pages was the big learning focus of my weekend. Our project was to use Nokogiri to scrape the Flatiron student webpage for information on each student and export that data into an SQL database. It took a lot of trial and error playing around with Nokogiri before we figured things out, but by the end my whole group was pretty comfortable navigating the trees of data that is HTML.

We also had to redo the quiz from week one but make it object oriented, having to have classes in each of the previous tests. I thought the difficulty on that assignment was pretty easy but that it was useful in providing repetition in looking at grouping things as a class.

Lastly we were given an assignment called playlister, which was a multi-file, multi-class assignment that had a suite of rspec tests that needed to be passed. I sure hope this was the stretch assignment for the weekend as I spent a lot of time struggling with it.

I’m really looking forward to week three. After two weeks I’m already amazed at the tools we’re beginning to scratch the surface of using. I can’t imagine after 10 more weeks how many cool things we’ll be able to build. I feel like a child who just learned what a car can do but whose feet can’t yet reach the pedals. Once they can it’s going to be a fun time!

Flatiron School Day Eleven

| Comments

Day Eleven kicked off a day of very little actual Ruby. In the morning we worked on a debugging project where we were handed some broken ruby code and the expectations for how it was supposed to work and had to fix it. I really enjoyed that project, as much as I like building new things its also fun to fix broken stuff. After that though, the rest of the day was spent on SQL.

Something I like about Flatiron is that we learn everything from the ground up. The magic of a lot of things like Rails and Active Record will be understood by us as we will have learned to do everything without them. That is exactly how I want to learn to program. That said, it’s also a pain in the butt. Writing SQL queries isn’t conceptually difficult, though the new syntax creates some conflicts, but writing it in sublime as a .sql file and smashing it into a DB in BASH is a more tedious process than I think is probably necessary. I’m about ready for Active Record!

Most of the classes issues seemed to stem from Queries and Joins. Most of the organizing of the databases came pretty naturally to most people I talked to, but there is a lot of syntax with queries/joins that can be pretty confusing. I’m going to post a snippit of my code and try and explain it…

Queries and Joins
1
2
3
4
5
6
7
8
9
SELECT project.title, SUM(pledge.amount) AS 'total_pledge_amount'
FROM
project
INNER JOIN
pledge
ON
project.id = pledge.project_id
GROUP BY
project.title;

So, this query has several parts which I will try and explain correctly one at a time.

The first is SELECT. This is the specific data we want this query to look at. In this case its the ‘title’ column from the ‘project’ table and the sum of the ‘amount’ column from the ‘pledge’ table. The AS key just renames the result of the SUM function to ‘total_pledge_amount’ and could be removed and the query would still function. Next is FROM, we are joining from the project table, using an INNER JOIN with the pledge table. I reversed the places of project and pledge and got the same results, so I’m not yet sure where it would be important to specify one table in front of another. After that is ON, which is where the JOIN will link the two tables based on a mutual key. In this case its the primary key of project (project.id) and the foreign key in pledge that corresponds with the project primary key (pledge.project_id). Lastly is GROUP BY for which i put ‘project.title’ this orders the query results alphabetically by the ‘title’ column in the ‘project’ table. The result is a list of each project.title and the total amount of pledges that match each projects key.