Friday, May 9, 2014

Hierarchical Database Structure - NoSQL (MongoDB)

Hierarchical Database Structure - NoSQL

As a follow up to my last blog post on Hierarchical Database Structures (SQL), I will attempt to code the same hierarchical database structure, but with MongoDB. 

Let's start my creating a database

  $ mongo heirarchy

This database is going to be saved here


I am going to save all the data, using the children method. 

  db.categories.insert( { _id: "7", children: [] } )
  db.categories.insert( { _id: "8", children: [] } )
  db.categories.insert( { _id: "9", children: [] } )
  db.categories.insert( { _id: "1", children: [] } )

  db.categories.insert( { _id: "4", children: ["7", "8"] } )
  db.categories.insert( { _id: "5", children: ["9", "1"] } )

  db.categories.insert( { _id: "2", children: ["4", "5"] } )

Run a Query to get to the Second Level of Data

  db.categories.findOne( { _id: "2" } ).children
  => [ "4", "5" ]

Compared the follow SQL, The NOSQL method of querying data is incredibly clean. 

   SELECT child FROM tree WHERE parent = 
       ( SELECT child FROM tree WHERE parent IS NULL );  

Index Creation

  db.categories.ensureIndex( { children: 1 } )

Find all parents of a specific node

  db.categories.find ( { children: "1" } )
  => { "_id" : "5", "children" : [  "9",  "1" ] }

- Notice that the precious query thinking the parents of 1 is both 5 & 9. 
- This shows that the child structure is useful for looking at data with a node, might have multiple parents. 

Wednesday, April 30, 2014

Hierarchical Database Structures

Hierarchical Database Structures (SQL)

Let's look at a visual diagram of the following data structure and explore some alternative options.

Option 1: Relational Database - Single Table
- Let's take a look at how we could structure this data in a relational database in a single table.

CREATE TABLE tree( parent INTEGER, child INTEGER );
Ect... Until we have the following table. 

table_name = tree
Parent | Child
  Null   |     2
  2        |      4
  2        |      5
  4        |      7
  4        |      8
  5        |      9
  5        |      1

Question: How can we return the second level of data for this tree? 

ANSWER 1: Since the table was set up correctly, we know that the child who has a parent of NULL is the head of the table and then we want to move down a level from there. 

   SELECT child FROM tree WHERE parent = 
     ( SELECT child FROM tree WHERE parent IS NULL );          

Answer 2: What do we do if the developer decides to not clue us into the fact the a child of 2 doesn't have a head?  

Parent | Child                  Parent | Child
  Null   |     2                        2        |      4
  2        |      4                       2        |      5
  2        |      5          =>        4        |      7
  4        |      7                       4        |      8
  4        |      8                       5        |      9
  5        |      9                       5        |      1
  5        |      1                                          

- We no longer have an easy path to the head of the table. 
- Let's use SQL to make this Table Join itself. I know this sounds crazy. Let's take it in steps.

  Step 1 - Make the JOIN, User Inner

  SELECT * FROM tree JOIN tree AS tree_clone WHERE tree.parent = tree_clone.child;

Results (All of the possible paths through the maze). Notice has two repeats. 

Looks like I didn't get everything I wanted. However, if we perform an OUTER JOIN we will get the additional information in return. 

  Step 3 - Try an Outer Join for more results

SELECT tree.parent FROM tree AS tree_clone LEFT OUTER JOIN tree ON tree.child = tree_clone.parent;

Results (Notice that we received two additional columns that don't match any values. Pretty Cool).
2|4| |
2|5| |

- We can use SQL to Join to table onto itself in order to traverse all of the different path through the hierarchy. In order to move down a row we need to gather additional information. 

Tuesday, April 22, 2014

jQuery Cookie - How to make a CSS change persist between page requests.

jQuery Cookie and Changing CSS between page requests.

I was recently working on a jQuery function to show the third column of a table. My difficulty existing in persisting this state change between user requests. Here is my method using.

.table { td:nth-child(3){ text-align: right; width: 90px; visibility: hidden; } }
.make_visible { visibility: visible !important; }
$('.howAmIDoing').on('click', function() { $('.table td:nth-child(3)').toggleClass("make_visible"); if ($.cookie('compare-medium') == 'true'){ $.removeCookie('compare-medium'); } else { $.cookie('compare-medium', 'true') } }); if($.cookie('compare-medium') == 'true'){ $('.table td:nth-child(3)').addClass("make_visible"); };
What is Happening?
1. By default every third column on the table's visibility is set to hidden.
2. On click I use the jQuery toggleClass method to add a CSS class with a higher specificity to make the third column visible.
3. When this is occurs, I write to the cookie.
4. On page load if that cookie exists add the class.
5. If the button is clicked again, I remove the css class

Monday, March 24, 2014

Paper Clip Gem

Paper Clip Gem - Review

Paperclip is a gem used for attaching to Rails applications.

Show View
<%= image_tag @user.user_photo.url %>
<%= image_tag @user.user_photo.url(:medium) %>
<%= image_tag @user.user_photo.url(:thumb) %>

Important Finds

:thumb => "200x200#"
The # signifies that this image is going to be saved as as a square on the inside of the photo. This is very useful for user profile pictures.

:medium => "300>x300"
This ensures that the image will have a a width greater than 300 px. 

Profile Pictures

User has_many UserPhotos

- I started by saving a bolean field on the UserPhoto to check if there is a default photo.
- I later found out that it is better to save a link on the user model

How to Link to AWS Account

- It is a a bad idea to save images to the project. Amazon Web Server and Heroku work well together in order to save files at a cheap fast cost.

Monday, March 10, 2014

Class Instance Variables

Use Class instance Variables

We all know that class variables such as @@ are dangerous to use due to their leaky inheritance.

<script src=""></script>class Presentaion < Document


 The class << self syntax opens up a classes singleton class.
  This allows you to specialize the behavior of methods called on that specific object.

  <Singleton Class>

Singleton Method is a method that is defined for exactly one object instance.

The <Singleton Class> is only invoked when it is filled with something.

  - An example of this is a method on an instance variable.

hand_built_stub_printer =
def hand_built_stub_printer.avaiable?

Sunday, February 23, 2014

Behavior Driven Development

Testing - Behavior Driven Development


The trouble with writing TDD testing is that too many developers focus on “How” when writing their unit tests, so they end up with tests that only confirm what the system does. It is really a feature driven approach to TDD. Some even say that BDD is just TDD done correctly.

BDD focuses on telling stories.

Side Note:

Unit Tests
- Tests that a relatively small piece of code is doing what is is intended to do.
- These follow the white box method and testing the inputs and the outputs of a test.

Integration Test
- This is done to demonstrate that different pieces of the system work together. Integration tests cover whole applications and require much less effort to implement.


- Does not actually write code, but it provides syntax and context for them to actually be  written.

Feature: Manage Articles
 In order to make a blog
 As an Author
 I want to create and manage articles

Scenario: Articles List
 Given I have articles title Pizza, Breadsticks
 When I go to the list of articles
 Then I should see “Piazza
 And I should see “Breadsticks”

Capybara - Simulate Users

Capybara is used for high level tests in addition to Test Driven Development to simulate how a user interacts with an application.

- It Clicks on things.

The DSL (Domain Specific Language)

Navigation  - visit(‘/home’)

Click Links and Buttons - click_link(‘id-of-link’)

Interacting with Forms - fill_in(‘First Name’, :with => ‘Thomas)

Querying - page.has_selector(‘table tr’)

Finding - find_link(‘hello’).visible?

within(‘li#movie’) do
 fill_in ‘Name’, :with => ‘Jimmy’

Scripting (JavaScript)

page.should have_content(‘baz’)

The default wait time is 2 seconds between requests, but it can be changed.
Capybara.default_wait_time = 5

Monday, February 10, 2014

Default Arguments

I want access to my variables.

There are a number of ways to pass in variables into ruby methods. After my first week at The Flatiron School I initially struggled with passing variable parameters into a function. Within this blog post I will introduce the different ways to pass in variables to a functions.

Required Arguments

def my_method(a, b)
  puts a
  puts b

my_method(25, "hello world")
 # => 25
 # => "hello world"

This method may only be called if both a & b are passed in.

# => "wrong number of arguments (1 for 2)"

If just pass in one method is passed in we will receive the error "wrong number of arguments"

Default Arguments

One to avoid this issue is to pass in a variable as a default argument.

def my_method(a, b="hello world")
  puts a
  puts b

In this example b has a default value of "hello, world". If only one variable is passed in this function, will still run.

# => 25
# => "hello world

Within Other Functions

A third way of getting variables into a function is by saving the variables into another function. I found this useful, if I didn't want to add the same arguments every time.

def add_variable
  hash1 = { :name => thomas, :email => }

def my_method

In this example I gain access to the variable hash1 without actually passing it into the function via an argument.