Archaic Positives

Adventurer, Traveler, Rubyist

Questions and Thoughts About Cucumber for Myself

Questions:

  • Why does a ActionController::RoutingError pop up even though all of the scenario steps are passing? This has been a recurring issue.
  • This was breaking because of ‘visit admin_partner_path(@user)’ that was in the final step of /step_definitions/admin_user_change_password.rb
  • How explicit must I be when testing a feature? What’s the balance between being too explicit in my feature testing, and not covering everything that should be tested?

Tips regarding Cucumber:

  • Backgrounds should only be used when you have shared context, but should be used sparingly
  • Want to frame our scenarios with user-driven language, not task-specific language
  • Given is used to identify your starting point; if you’re testing a password feature, then you should be on the ‘Edit’ page for the User
  • When is used to specify an Action of some kind; never use an assertion in a When clause
  • Then is where you make assertions for the test

Warden:

  • Warden test helpers for Cucumber will automatically log you in for a test without actually walking through the login steps
features/support/warden.rb
1
2
3
Warden.test_mode!
World Warden::Test::Helpers
After { Warden.test_reset! }
  • Only time, from this point forward, that you should visit and fill-in a login form is if you’re explicitly testing the login feature
  • If you need to be logged in as a Partner, use the Given I am logged in as a Partner step. Same for other AdminUser roles as well.
  • FactoryGirl helpers in cucumber will enable you to implicitly imply FactoryGirl object
features/support/env.rb
1
World(FactoryGirl::Syntax:Methods)

Rails Link Shortener App

Over the last few days, there were primarily two things that I wanted to delve into conceptually and understand: MongoDB and the logic behind a link shortener. I decided to combine the two of these and create a simple Rails app in which you could shorten links.

So, what is MongoDB? MongoDB is what’s called a NoSQL database technology. A NoSQL database doesn’t rely on a series of rows and columns within tables like a SQL, or relational, database does. NoSQL databases can store information in a variety of ways, but in the case of MongoDB, it stores it via a document database. Each respective document that you enter into the Mongo database is very similar to a JSON object in that they have a key-value store. However, the primary difference is that you do not access the documents via the key (think of accessing elements in a hash), but rather you query the database for these document elements.

I started out the app by generating a new Rails app via rails g new link_shortener. Once the app is generated, you can also use the Mongoid gem to generate the config file for the MongoDB database via rails g mongoid:config. Once you generate the config file, you can read through the file, available at mongoid.yml within the app, for an in-depth explanation of Mongoid’s capabilities.

Next step is to create the model. Since we have an app t hat is going to shorten URLs, we need to create a URL model, so that each URL can be represented within Ruby/Rails as an object.

In Rails, querying the database is very much like that of ActiveRecord. The same model commands, such as where, find, find_or_create_by, save are very much in place. Look at the Mongoid documentation to find out more.

Let’s test it out.

Url Model
1
2
3
4
5
6
7
8
9
10
11
u = Url.new
u.url = "http://irmiller22.github.io"
#=> #<Url _id: 52eeacee49524d08ce010000, url: "http://irmiller22.github.io">

u.save
Url.where(:url => "http://irmiller22.github.io")
#=> #<Mongoid::Criteria
#=>  selector: {"url"=>"http://irmiller22.github.io"}
#=>  options:  {}
#=>  class:    Url
#=>  embedded: false>

Now that you’ve set up a model to take care of persisting data to the database, we need a controller to eventually take the input, generate the right output, and getting the data to the appropriate routing destination. Let’s generate the new controller: rails g controller urls new. Typically when you generate a controller, you generate all 7 of the RESTful actions, but in this case we’re only interested in testing one action for the moment: new. This generates the following:

UrlsController
1
2
3
4
class UrlsController < ApplicationController
  def new
  end
end
routes.rb
1
2
3
get "urls/new"
# we will modify this to the following:
# resources :urls, only: [:new, :show, :create]

Now let’s fill in the logic for each of the actions in the Url controller.

UrlsController
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class UrlsController < ApplicationController
  def new
      @short_url = Url.new
  end

  def create
      @short_url = Url.new(url_params)
      if @short_url.save
          flash[:short_id] = @short_url.id
          redirect_to new_url_url
      else
          render :action => "new"
      end
  end

  def show
      @short_url = Url.find(params[:id])
      redirect_to @short_url.url
  end

  private

  def url_params
      params.require(:url).permit(:url)
  end
end

In this simple case, I’ll be resetting the link to the domain and the URL id, so it would look like this while running locally: localhost:3000/f3e200091. In my next refactor, I’ll end up generating a random string, but this will do for now.

Let’s move on to the views:

application.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
  <title>LinkShortener</title>
  <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
  <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
  <%= csrf_meta_tags %>
</head>
<body>

<%= yield %>

<% if flash[:short_id].present? %>
 <p class='shortened_link'>
      The shortened URL is available <%= link_to "here", url_url(flash[:short_id]) %>
     (Right click and copy link to share it).
 </p>
<% end %>

</body>
</html>
new.html.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%= form_for @short_url do |f| %>
 
 <p>
     <%= f.label :url, "Your URL:" %>
     <%= f.text_field :url %>
  </p>

 <% if @short_url.errors[:url].any? %>
     <p class="error_messages">
         The given URL <%= @short_url.errors[:url].to_sentence %>
     </p>
  <% end %>

 <p class="button">
      <%= f.submit "Shorten my URL" %>
 </p>

<% end %>

These two views are all you need to enable the link shortener. Fire up the rails server, and see your new link shortener in action!
EDIT: I incorrectly asserted that a MongoDB document element is similar to that of a key-value pair, and the appropriate revisions have been made. Many thanks to Myles Recny for catching that error.

SCALA Basics: An Introduction

Scala is a programming language meant to address scalability issues that confront a large number of developers today. It is a statically typed language, meaning that it binds a type to a variable for the variable’s lifetime, whereas dynamically typed languages bind the type to the value referenced by a variable. Simply, statically typed variables are immutable, whereas dynamically typed variables are mutable. Scala also supports both functional and object-oriented programming. It seems that these attributes would conflict with one another, but the argument is that both attributes in conjunction lead to synergies in both performance and architecture.

Let’s get started on the introduction.

Print Out a String
1
2
3
4
val book = "Let's start learning about Scala"
// java.lang.String = Let's start learning about Scala
println(book)
// Let's start learning about Scala

val is used to declare a read-only variable named book. In the next exercise, let’s create a class that will take a number of parameters and then upcase them. We’ll also refactor this function to make it more efficient and readable. Let’s do it in the space below:

Upper Case Function
1
2
3
4
5
class Upper {
  def upper(strings: String*): Seq[String] = {
      strings.map((s:String) => s.toUpperCase())
  }
}

We’ve defined the class Upper, and specified its parameter strings as an undefined number of string values, evidenced by the splat in String*. Then we specify the return type Seq[String] as a collection (or array) of strings. Then inside of the method’s body, where we call the map method on the strings array, and passed in (s:String) => s.toUpperCase() as a function literal. In other words, it executes that function for each mapped parameter of the array strings.

Now let’s initialize the Upper Case Function below:

Initializing Upper Case Function
1
2
3
val up = new Upper
Console.println(up.upper("run","ian","Fly","hero"))
// Array(RUN, IAN, FLY, HERO)

The upper method in the Upper class converts each parameter into an uppercase string, and returns them in an array.

Now let’s refactor.

Upper Case Function Refactored #1
1
2
3
4
5
object Upper {
  def upper(strings: String*) = strings.map(_.toUpperCase())
}
println(Upper.upper("run","ian","Fly","hero"))
// Array(RUN, IAN, FLY, HERO)

We’ve now declared an object, which in Scala is a singleton. In this situation, we only ever need one instance of Upper run at a time, so a singleton works appropriately. The _ element inside of the map method is a placeholder variable that each string element will be assigned to before toUpperCase() is applied.

This is the first day I’ve used Scala, and my first impression is that it’s a lot like a hybrid of Ruby and Java/JavaScript. I still need to get better at understanding how collections are referenced to and organized inside of functions, but I’m looking forward to learning more Scala.

JavaScript Basics: An Introduction

Variable Declaration and Constant

Variables
1
2
3
var x = 10,
      y = 30,
      myMath = x + y;

myMath in this case is the sum of variables x and y, which would be equal to 40.

Constant
1
2
//const is a keyword that will declare a constant
const CONSTANT = 22;

To find out what data type a variable is, you use the typeof method, as shown below:

Typeof method
1
2
3
4
5
6
const CAR = 2;
console.log(typeof CAR);
//--> number
var string = "hello";
console.log(typeof string);
//--> string

Conditional Statements

You can also use an if/else statement to execute a given statement if a certain condition is true. For example, if you wanted to check and see if a variable was considered a type of string, you’d do the following:

Conditional
1
2
3
4
5
6
var name = "Ian";
if(typeof(name) == "string"){
  console.log("It is a string.");
}else{
  console.log("It ain't a string.");
}

Local vs. Global Scope

Local vs. Global Scope
1
2
3
4
5
6
7
8
9
10
11
12
var x = 5;
var y = 10;

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

function subtract(a,b){
  var y = a - b;
  return y;
}

The x and y variables that are outside of the add and subtract functions are called global variables. They are declared outside of a function in the global scope, and are essentially accessible from anywhere inside of the program.

Functions create a new scope. The x variable inside the add function and the y variable inside of the subtract function are known as local variables. They exist only in the context of the respective function, and are not accessible outside of the function. Think of it as the Vegas motto; what happens here, stays here.

Arrays in Javascript

Making a list inside of our app would involve the following:

List in JS
1
var students = ["Ian Miller", "James Wood", "Saron Yitbarek", "John Cafferty"];

Looping Through Arrays

Looping Through Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function trackStudents(name, roster){
  if (roster.length == 0){
      roster.push(name);
  } else{
      for(var i=0; i < roster.length; i++) {
          if(roster[i] == undefined){
              roster[i] = name;
              return roster;
          } else if (i == roster.length - 1) {
              roster.push(name);
          }
      }
  }
  return roster;
}

This is just a simple looping function that takes a roster, and adds a name to the roster array. If the array does not have any elements in it, then it will push that element onto the end of the array, which will be the first element. Otherwise, for each element in the array, if an array position is undefined, then it will set that element equal to the name value. Also, if it is the last element in the array, it will also push the name value to the end of the array. Finally, once the whole array has been iterated through, it will return the array.

These are mostly for me to remember and repeat. I’m currently branching out into other languages at the moment, and will be focusing on JS, jQuery, and Ajax.

How to Generate Mailers via Rails

One topic that we never covered in regards to Rails was how to properly generate mailers (automatically generated emails from a web application).

I’m covering this because I have not used mailers before, and I think it’s a pretty pertinent feature of Rails that everyone should know.

I’ll be using the example of a distributed solar generation product. Whenever a consumer is experiencing unusually low solar energy production or energy generation patterns consistent with a malfunctioning module, it will send out a mailer notifying them of these issues. In order to generate a mailer, you type in the following command:

Mailer Generation
1
rails g mailer SolarMailer error_report

The next step is to set up the default settings of the mailer.

Mailer Settings
1
2
3
4
5
6
7
class SolarMailer < ActionMailer::Base
  default from: "administrator@solartech.com"

  def error_report(panel, customer)
      mail to: customer.email, subject: "Panel #{panel.location} #{panel.id} is experiencing some technical issues.""
 end
end

After we have set up the default settings for the mailer, then we go to the Panel model in order to specify when the mailer should be sent out.

Panel model
1
2
3
4
5
6
7
8
9
10
class Panel < ActiveRecord::Base
  belongs_to :module
  before_save :check_power_yield

  def check_power_yield
      if power_yield <= 1200 kWh #base power generation
          SolarMailer.error_report(self, self.customer).deliver
      end
  end
end

That’s pretty much it for a basic mailer. You can style the mailer using HTML/CSS, and you can also add front-end features via Javascript (AJAX, jQuery).

Impetus for a Career in Programming

I’m currently on a flight over the continental US, on board Virgin America flight #27, headed from New York City to San Francisco, CA. Since I left NYC, I’ve been thinking a lot about my path to programming, and how I ultimately ended up in my current position. I think it’s a combination of several factors, most importantly the re-discovery of childhood pursuits.

Now for the moment of full disclosure: I have a severe hearing disability. I have roughly 75-85% hearing loss, and it’s hard to ascertain the exact number because it varies over time. I also think this fact goes a long ways towards explaining the meandering path behind me as I searched for my passion.

I’ve always had a pretty imaginative brain, always willing to go into wild tangents that test the limits of my creativity. I’m not sure if it’s a result of my brain’s capacity for randomness, or if it’s just my brain trying to make sense of the endless chatter being fired between the synapses of my neural pathways. Part of me is convinced that this is a result of my disability. When one of the five senses is limited (in this case, sound), another is enhanced. In my situation, I think my visual ability is much more nuanced than the average person. Perhaps that transfers over into my subconscious somehow, which would explain my visual acuity.

As a result of my hearing disability, I always enjoyed playing video games, particularly strategy games. It was something that gave me a full sense of control, something that I could, with 100% certainty, influence in terms of direction. In other words, it was an escape from the more difficult aspects of childhood, particularly my teenage years in which social interaction skyrocketed, leaving me behind my peers in social conversation.

From middle school until college, I was always interested in video games. As a result of video games, I started tinkering around with computers, my first experience coming when I figured out how to take control of my middle school’s computers using MS/DOS, and would perpetually confuse my fellow students by hijacking their mouse cursor and typing cryptic messages into their word processor application. I remember when I built my first website. It was a Geocities all-in-one basic site that focused on posting answers to my math homework. I don’t know if it was ever used at all by my classmates, but I remember the crappy blue background with the black and green Comic Sans font. Why did everyone use Comic Sans back then? What a colossal waste of a font. Anyways, the foundation of my technological curiosity had been firmly implanted by the time I was in middle school.

I was proficient in HTML and CSS back then, and was just starting to use JavaScript. I got so frustrated using JavaScript, largely because I was learning it on my own, and there were not many resources readily available in which you could find reliable answers. This is why having a community in which you can ask programming questions is so important. I lost my desire to continue my immersion into programming after a few months. Up until that point, many subjects came very easily to me then, such as English, Math, video games. I think the idea of a challenge discouraged me, and I was simply looking for something that provided instant gratification. I now realize that was a setback in terms of my mindset. Since then, the same question always came up from time to time: “what if?”. Looking back on it now, giving up was probably the biggest mistake I ever made.

Fast forward to my senior year of college. I was an Economics major, authoring a thesis that detailed solar energy subsidy programs and the long-term effects of that respective government’s approach. To summarize my thesis, among all countries with mature renewable energy policy programs, Germany did best in structuring a long-term approach while the United States bungled it. At that point, I was certain that I was going into a career in renewable energy finance or policy.

My career in renewable energy started off well. I became an intern at a very well respected renewable energy policy group in Washington, DC, and eventually wrote a white paper that discussed the merits of tax equity syndication for solar power development. At the conclusion of my internshp, I went to work for a biomass power startup, and gave me a wide breadth of expertise in project development in India and Tanzania.

In the spring of 2013, I decided to take an online course for Python on CourseRA just to play around with the idea of programming, not realizing that it would ultimately alter my career path 9 months later. Through Rice University’s Python class on CourseRA, we built a number of small games, such as Tic-Tac-Toe, Paddleboard, and a simple spaceship game that reminded me a little bit of a 2D version of Star Wars. I started to help out with web application development for my company, and the product was supposed to be a dashboard for energy analytics. First I helped write the business documentation for it, then started working with a programmer to build out the framework for the application itself. Over the course of 2 months of working with a programmer, I decided that programming was what I wanted to spend the rest of my life doing. The constant problem solving, discussions about best courses of action, and brainstorming was the most intellectually challenged and enriched that I had felt since high school and college. When you attain that desire for learning, you never really want to let it go. That desire siezes you like adrenaline does a bungee jumper jumping off a bridge: simply relentless.

I started taking courses on CourseAcademy and TeamTreehouse for Ruby. I had heard that Ruby was the hottest full-stack language at that point, and it was relatively straightforward to learn. I also applied to several boot camps, convinced that it was just what I needed to jumpstart my future. I ultimately settled on the Flatiron School in NYC because of its community-driven approach to programming, as well as its mission to help individuals find a passion in programming, and also encourage the involvement of women in what has been traditionally a male-dominated profession.

Fast forward five months later. I am two weeks out of boot camp at Flatiron School. Has it been worth it? The reasons may be different for everyone, but for me, it certainly has. I’d even go as far as to say that it’s been life changing. I’ve met the most wonderful group of individuals at Flatiron, and I’ve learned a lot from them. And I can now call myself a programmer. Not a skilled one yet, but that’s what I am working towards, step by step. But there are three important results that have been made possible by my experiences in the past year. I’ve discovered my passion. I’ve re-ignited my desire to learn. And I’ve finally learned the lesson that I should have learned long ago, even with a particularly limiting disability; there is no limit.

Microhaus App: Part I

Today I decided to build a microblog app. It is like a traditional blog, but it is private to a specific group of friends. There are other options out there for a microblog, but I wanted to create the experience for myself, and how I would customize it for my group of friends. After I finish the app, I plan to release it to my friends from college, and see what their feedback is.
I started out by creating a new app via rails. For the moment, I am calling the app “microhaus.” I came up with this name particularly because it’s a microblog, and it is accessible only to a small number of people (a circle of friends, if you will).

Generating the new app
1
rails g new microhaus

I then made changes to the Gemfile in order to reflect the gem and database preferences. This is what my gemfile currently looks like:

Gemfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
source 'https://rubygems.org'

gem 'rails', '4.0.1'

group :development do
  gem 'sqlite3'
end

gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'

group :test do
  gem 'better_errors'
  gem 'binding_of_caller'
  gem 'rspec-rails'
  gem 'capybara'
  gem 'cucumber-rails'
end

group :production do
  gem 'pg'
  gem 'rails_12factor'
end

group :doc do
  gem 'sdoc', require: false
end

I’ve set up my test, development, and production environments. Later on, I will add in other gems in order to enhance microhaus, but for the initial buildout process, these gems will do.

I also created a User scaffold, which instantiates a migration for User, a controller, resources, erb templates, stylesheets, and tests. After creating the scaffold, I ran the rake db:migrate command in order to migrate the Users table into the development database.

Secondly, I added a Post scaffold via the rails g scaffold Post content:string user_id:integer group_id:integer command. The idea is to have a post that belongs to a user, and can be viewed by a group in which the users have the corresponding group id. We want each post to be viewable by users of the same group.

At this point, I committed and pushed my changes up to Github.

The next step is to build out a secure token generator that will be used to verify cookies when a new login session is initialized. Here’s the code I used to set this up:

Secure Token Generator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
require 'securerandom'

def secure_token
  token_file = Rails.root.join('.secret')
  if File.exist?(token_file)
      File.read(token_file).chomp
  else
      token = SecureRandom.hex(64)
      File.write(token_file, token)
      token
  end
end

Microhaus::Application.config.secret_key_base = secure_token

My approach to building an application closely mirrors that of Michael Hartl’s approach, so as he recommends, this would be a good time to start writing out some tests. I wrote out RSpec tests to make sure the “About, Home, and Contact” pages properly render as specified in my ERB templates.

RSpec Tests
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
describe "Static pages" do
  let(:base_title) { 'microhaus' }

  describe "Home page" do
      it "should have the content 'microhaus'" do
          visit '/static_pages/home'
          expect(page).to have_content("#{base_title}")
      end

      it "should not have the custom title 'Home'" do
          visit '/static_pages/home'
          expect(page).to_not have_title("| Home")
      end

      it "should have the base title" do
          visit '/static_pages/home'
          expect(page).to have_title("microhaus")
      end
  end

  describe "About page" do
      it "should have the title 'About'" do
          visit '/static_pages/about'
          expect(page).to have_title("#{base_title} | About")
      end
  end

  describe "Contact page" do
      it "should have the title 'Contact'" do
          visit '/static_pages/contact'
          expect(page).to have_title("#{base_title} | Contact")
      end
  end
end

At this point, we have the basic building blocks in place that are necessary to horizontally plan out our application structure. Once that structure is in place, then we can start building the application vertically, and make changes/additions as necessary.

The next step is to start building out the functionality for the ERB templates and also to build out the corresponding RSpec tests to ensure that the functionality is there. These concepts will be covered in the next “Microhaus” post.

Big O Notation

Big O Notation is simply a measure of an algorithm’s performance. It focuses on two primary components: speed and size. It also presents a best-case scenario of an algorithm as well as a worst-case scenario.

There are four primary scenarios that the majority of individuals will deal with in Big O Notation: O(1), O(n), O(n2), and O(log n).

The O(1) case simply refers to an algorithm in which the performance result is the same no matter the size of the input. For example, a change in the value of a pre-existing array element will not change the time it takes to execute the algorithm.

O(1)
1
2
3
4
5
6
7
8
9
array = [1,2,3,4,5]

def is_1?(array)
  if array[0] == 1
      return true
  else
      return false
  end
end

The O(n) case is an algorithm that iterates over a range of elements, and the performance result increases for each additional element in the collection. If it took 1 second to iterate through each element and I had a total of 10 elements in my collection, it would take 10 seconds (10/1). If I had 500 elements in my collection, it would take 50 seconds (500/10).

The example below is a worst case scenario. Since 10 is the last element in array, the each method won’t break until it has run through and compared every value in the method. If the comparator value were 1, then it would result in the best case scenario of O(1). With every each statement that is used for comparison, it is always assumed that the worst case scenario is O(n), or the total size of the array.

O(n)
1
2
3
4
5
6
7
array = [1,2,3,4,5,6,7,8,9,10]

def comparison?(array)

array.each do |x|
  break if x == 10
end

The O(n2) case refers to a function whose performance increases in proportion to the square of the input size. When an additional element is added to a collection, then the performance result will increase by the square of n. This is particularly common in cases where you are iterating with nested loops. You can take this even further: a nested loop with deeper iterations will result in a higher power value for n. A loop with 2 nested loops inside of it will result in O(n3). A well known example of this is the bubble sort.

O(n^2)
1
2
3
4
5
6
7
8
9
10
11
array = [8,1,9,7,5,3,2]

def bubble_sort(array)
  array.each_index do |x|
      (array.length - x - 1).times do |element|
          if array[element] > array[element + 1]
              array[element], array[element + 1] = array[element + 1], array[element]
          end
      end
  end
end

The O(log n) case is an algorithm that selects the middle element of the collection, and compares it against a specific value. If the value is higher than the middle element, it will perform the same operation against the upper half of the collection. If the value is lower than the middle element, it’ll perform the same operation against the lower half. It keeps splitting each respective collection until it finds the element it’s looking for, or until all possibilities have been exhausted. An example of this is the merge sort.

O(log n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
array = [8,7,3,2,5,1,4,9,6]

def merge_sort(array)
  return array if array.size < 2
  left = array[0, array.length/2]
  right = array[array.length/2, array.length-1]

  merge(merge_sort(left), merge_sort(right))
end

def merge(left, right)
  sorted_array = []
  until left.empty? || right.empty?
      sorted_array << (left[0] <= right[0] ? left.shift : right.shift)
  end
  sorted_array.concat(left).concat(right)
  p sorted_array
end

The Art of a Question

For once, I want to take a break from exploring programming topics, and explore the rationale behind asking the right question. Or rather, is it insomuch asking the right question, or guiding yourself in the right direction? I think it is a little bit of both, with more emphasis on guidance. It’s not so much the silver-bullet question that will find you the answers, but it’s a series of small, seemingly mundane questions that will ultimately lead to the epiphany where all of the previously perplexing concepts suddenly click together into a cohesive abstraction.

From time to time, I have found myself unable to ask the right questions. It’s as if there is a mental block in my head, unable to move forward beyond an obstacle, a metaphorical wrench stuck in the gears of my neocortex. When that process unfolds, it is easy to doubt yourself and your ability to lead yourself out of the quagmire. There is a reason why many individuals are daunted by the prospect of learning how to program. It is a seemingly endless black hole that manifests itself as a negative feedback loop. Despite the organized chaos that arises, most often overlook the key decision making component of programming: knowing where to start.

Knowing where to start isn’t even the be-all-end-all solution to asking the right question. It is simply a starting place. Just because a runner starts at mile 0.0 after a starter pistol has fired, it does not mean that failure is imminent. It is a mindset. A runner tackles a marathon one step at a time. Step by step, two feet turns into 10. 10 feet turns into a mile. A mile turns into 10 miles. 10 miles turn into 20. It’s about breaking down the obstacle into manageable parts, and moving on from segment to segment. This works because of two reasons: one, it keeps the logical decision making process flowing, and two, it pushes doubt and negative reinforcement to the periphery of human consciousness.

I read an article the other day discussing a concept called cognitive load. According to George Miller, an eminent psychologist who taught at Princeton in the 1950’s, our brain can realistically hold about seven pieces of information simultaneously at one point in time. That number has since been revised to three or four. This is a significant problem in the information age. WIth historically recent advents such as the Internet, we are overly stimulated by the free flow of information, made possible largely by electronic devices. Information enters and exits our cognitive consciousness that we don’t grasp a basic level of understanding. We are unable to transfer it from our short-term to long-term memory stores, and consequently our ability to think critically and conceptually weakens. Ergo, one step at a time.

So it seems that there are valid reasons, backed by science, psychology, and other studies focused on the human brain, that call for the fragmentation of a complete problem into parts. If someone were to ask the question, “how does a route ultimately render a view in a Rails project?” This is my thinking process below.

First off, there are multiple steps that between the route path and the view being rendered. In MVC, there are typically eight steps in the chain of events.

First, a browser sends a request to the Rails router.  
Second, a router sends the request to the respective controller.  
Third, the controller asks the model to retrieve the respective data needed for the request from the database.  
Fourth, the database sends that data back to the model.  
Fifth, the model sends the retrieved data back to the controller.  
Sixth, the data, encapsulated within the logic defined in the controller, is sent to the view.  Seventh, the view renders the data into the HTML page and is sent back to the controller.
Eighth, and finally, the controller sends the view action back to the browser where it is rendered.

This is an oversimplified example, but the question went from a generic question about a route and respective view rendering to a multifaceted question made up of smaller implicit questions about the 8 steps of MVC progression. Each step can also be broken down further to better understand the process. Each little question is a foundation that can be built upon, and will ultimately to a deep understanding of how a simple Rails application works.

So perhaps the best question is not simply a targeted question that seeks a one-dimensional answer, but rather a series of smaller, more basic questions derived from a larger question. Simplicity is the best form of policy. Start somewhere. Plant your flag in the sand. Let your initial question, and the subsequent chain of questions, be your guide.

ActiveRecord: Validations

Validations are necessary to prevent invalid data from being persisted into the database. They are necessary to allow for efficient data entry and processing, and prevent uncessary situations such as empty user-name fields pushing empty strings into a database.

ActiveRecord has a number of simple declarative validations, such as validates_absence_of, validates_acceptance_of, and validates_confirmation_of. The one validation that I think would come in quite handy is the validates_format_of validation. According to the “Rails 4 Way”, it’s heavily dependent upon regular expressions, but it’s an invaluable way to check the formats of email addresses, web URIs, etc.

You can also place constraints upon your validations. For example, if you’re using validates_length_of for usernames, you can specify a range that the length must fall between. For example:

Validation - Username Length
1
2
3
class Account < ActiveRecord::Base
  validates_length_of :username, within: 5..20
end

If it exceeds the length, then you can provide an error message option that follows the validation.

Validation - Username Length, Error
1
2
3
class Account < ActiveRecord::Base
  validates_length_of :username, within: 5..20,                 wrong_length: "should be %{count} characters            long"
end

An important aspect of validations is enforcing uniqueness among join models in the database. We have used this recently (in our Flatiron-Kitchen-Ruby-003 assignment). In order to enforce uniqueness, we have to define a scope constraint. For example, if we had three classes, Registration, Course and Student, how could we make sure that a student isn’t registered more than once for a particular class? We would define the scope of the Registration class, as shown below:

Registration - Scope
1
2
3
4
5
class Registration < ActiveRecord::Base
  belongs_to :student
  belongs_to :course

  validates_uniqueness_of :student_id, scope: :course_id, message: "can only register once per course"

Another one that you run into all the time:

Email Validation
1
2
3
class Email < ActiveRecord::Base
  validates_uniqueness_of :address, message: "already taken"
end

In short, validations help you place constraints upon your code to make it less error-prone in regards to data persistence. Think of validations as a gatekeeper for your application data – it lets the good pieces in, and keeps the bad ones out, assuming that you have the proper constraints in place.