Super Computer.

Instructions for Implementing Friendly ID

Step-by-step instructions for implementing Friendly ID in a Rails app.

You already know RESTful urls are n00b sauce, otherwise you wouldn’t be here.

If you’re not familiar, Friendly ID is a sweet gem that turns Rails standard RESTful urls (e.g. /users/1/) into more friendly and best practice string-based urls (e.g. /chris-lake)

The following instructions were curated from Norman Clarke’s complete documentation and Ryan Bates’s RailsCast — because the former is more in-depth than necessary for your run of the mill Rails app, and the latter is not quite deep enough.

Add FriendlyID to your Rails app’s gemfile.

gem 'friendly_id', '5.0.0.beta4' #=> Or whatever the current version is.

From terminal run bundle install, per usual:

$ bundle install

For all the models you want to add FriendlyId’s, run the following migration.

$ rails g migration add_slug_to_[your model name here] slug:string

Ryan Bates says it’s a good idea to add an index for finding records, and at this point in my coding career, I’m a follow Ryan Bates’s advice. (Btw, that dude is the man. I hope he takes the time he needs to get his head straight.)

In the migration file – let’s use a User model by way of example – /db/migrate/20120101000000_add_slug_to_user.rb, add the index like so.

class AddSlugToUsers < ActiveRecord::Migration 
  def change
    add_column :users, :slug, :string
    add_index :users, :slug, unique: true
  end
end

Please remember to run the migration.

$ rake db:migrate

To fill the slug in for existing records, we need to go into each record and save it.

$ rails c
> User.find_each(&:save)

We’ll want our slugs to update when records are changed in the db. At the same time it seems to be a good practice to still recognize older slugs and their legacy urls. We can do this by using FriendlyID’s history option in our model /app/models/user.rb.

class User < ActiveRecord::Base
  extend FriendlyId
  friendly_id :name, use: [:slugged, :history]
end

This history needs to be stored somewhere so you’ll also want to add a table to your database schema to store the slug records. FriendlyID provides a generator for this purpose:

$ rails generate friendly_id

And again.

$ rake db:migrate

Ryan Bates points out that, at this point, if our customer visits a legacy url, it will just work. Better would be to redirect them to the new url. We can do this by adjusting the show page on the controller – /app/controllers/users_controller.rb

Not sure if I’ll even bother implementing this, but here’s the syntax.

def show
  @user = User.find(params[:id])
  if request.path != user_path(@user)
    redirect_to @user, status: :moved_permanently
  end
end

Quickly Creating a New Rails App

Cheat sheet for creating a new Rails app, adapted from the excellent Rails Guides

Create a new project

$ rails new <project name>

Switch into the correct folder

$ cd <project name>

Get the database up

$ rake db:create

To start the rails server:

$ rails s

Create a controller

$ rails generate controller home index

If you’re using Rails v3.2.13, remove the default home page

$ rm public/index.html

Open config/routes.rb and uncomment the root url route

root :to => "home#index"

Scaffold a resource

$ rails generate scaffold <Model_Name> column_name:data_type column_name:data_type 

Run another migration

$ rake db:migrate

Variable Scope in Ruby

Variable Scope in Ruby

Defining scope between Global, Class, Instance and Local variables in Ruby

If you’re learning Ruby, one of the first concepts you’ll likely encounter – after Objects and Classes – is the concept of variables and how they differ by “scope.”

For this post I’ll focus on the latter point and try to illustrate how scope is defined across the different kinds of variables available to the Ruby programmer.

Ruby Variables

  • Local variables. Expressed lower case e.g. var, str, fido, pommes_frites

  • Instance variables. Can start with lower or upper case letters. Can’t miss with their prepended ‘@’ sign e.g. @user, @bike, @Selfie

  • Class variables. Same rules apply as with their instance cousins, only prettier (or uglier, depending on your pov) with the double ‘@’ signs in front! @@User, @@parcheesi, @@Brooklyn

  • Global variables. They’re like pawns in chess who make it to the back row: they can be whatever they want, whenever they want (so long as they begin with a ‘$’ sign). Upper case. Lower case. Periods. Colons. Eat your heart out. $9, $!!, $foo_bar, $AmericasGotTalent, $meow

Now that you see how to tell the variables apart, let’s play with some example code to begin distinguishing between each variable’s scope.

Ruby variables at the class level

Let’s create a class and create an example of each variable.

class Verryables
  print local_var = "local var at class level"
  p @instance = "instance var at class level"
  p @@class_var = "class var at class level"
  p $GlobalVar = "global var at class level"
end

Simple. Run the code and you get exactly what you’d expect.

  #=> "local var at class level"
  #=> "instance var at class level"
  #=> "class var at class level"
  #=> "global var at class level"

Ruby variables and class instance methods

Now let’s define an instance method to see what happens when we (i) try to print the above class level variables, and (ii) reassign the variables.

class Verryables
  ...

  def instance_method
    p local_var
    p @instance
    p @@class_var
    p $GlobalVar
  end

  def second_instance_method
    puts "second instance method"
    p @instance
    p @@class_var
    p $GlobalVar
  end
end

What do you think the result would be? If you’re new to Ruby, think for a minute about what you expect will happen when we run it…

Survey says:

#=> "undefined local variable"
#=> nil
#=> "class var at class level"
#=> "global var at class level"

#=> "second instance method"
#=> nil
#=> "class var at class level"
#=> "global var at class level"

Is that what you were expecting? Now let’s play around and try to see what happens if we reassign (or define, as the case may be) these variables.

Testing scope between class methods and instance methods

Here we’ll change the messages, print them, and then go back up to the class level and print out the original variables to demonstrate which variables changed and which stayed the same.

class Verryables
  puts ">> class level definitions"
  p local_var   = "local var at class level"
  p @instance   = "instance var at class level"
  p @@class_var = "class var at class level"
  p $GlobalVar  = "global var at class level"

  def instance_method
    puts ">> begin instance method"
    # p local_var (commented out, else "undefined local var" blows up the program)
    p @instance
    p @@class_var
    p $GlobalVar
    puts ">> assigned and reassigned, as the case may be"
    p local_var     = "local var from instance_method"
    p @instance     = "instance var from instance_method"
    p @@class_var   = "class var from instance_method"
    p $GlobalVar    = "global var from instance_method"
  end

  def second_instance_method
    puts ">> second instance method"
    p @instance
    p @@class_var
    p $GlobalVar
  end

  def self.class_method
    puts ">> begin class method"
    # p local_var #=> undefined local variable
    p @instance
    p @@class_var
    p $GlobalVar
  end
end

The action here will be in the second set of print outs (note: I’ve added a puts messages at the beginning of each method to help us see what messages are being printed from which method).

Survey says:

class Verryables
  puts ">> class level definitions"
  p local_var   = "local var at class level"
  p @instance   = "instance var at class level"
  p @@class_var = "class var at class level"
  p $GlobalVar  = "global var at class level"

  #=> ">> class level definitions"
  #=> "local var at class level"
  #=> "instance var at class level"
  #=> "class var at class level"
  #=> "global var at class level"


  def instance_method
    puts ">> begin instance method"
    # p local_var (commented out, else "undefined local var" blows up the program)
    p @instance
    p @@class_var
    p $GlobalVar
    puts ">> assigned and reassigned, as the case may be"
    p local_var     = "local var from instance_method"
    p @instance     = "instance var from instance_method"
    p @@class_var   = "class var from instance_method"
    p $GlobalVar    = "global var from instance_method"
  end

  #=> ">> begin instance method"
  #=> nil
  #=> "class var at class level"
  #=> "global var at class level"
  #=> ">> assigned and reassigned, as the case may be"
  #=> "local var from instance_method"
  #=> "instance var from instance_method"
  #=> "class var from instance_method"
  #=> "global var from instance_method"

  def second_instance_method
    puts ">> second instance method"
    # p local_var #=> undefined local variable
    p @instance
    p @@class_var
    p $GlobalVar
  end

  #=> ">> second instance method"
  #=> "instance var from instance_method"
  #=> "class var from instance_method"
  #=> "global var from instance_method"

  def self.class_method
    puts ">> begin class method"
    p local_var
    p @instance
    p @@class_var
    p $GlobalVar
  end

  #=> ">> begin class method"
  #=> undefined local variable
  #=> "instance var at class level"
  #=> "class var from instance_method"
  #=> "global var from instance_method"

end

Phew, that’s bordering on TL;DR but I hope at least it helps illustrate how each variable responds when changing scopes (in this case, we went from the Class level, down to an instance of the class, and then back up to the Class level).

Variables, further defined

Here’s the definition for each variable, and how the code above illustrates it.

  • Local variable (local_var in the earlier example).

    As the name implies, local variables have limited scope – within a method definition, for example. Local variables don’t survive the scope change between class definitions and their inner method definitions. As such, local variable names can be reused in different scopes.

    Using our earlier example, we could use the name local_var throughout the program, and so long as each usage was within a different scope, each local_var will be treated as completely separate.

    That’s why, despite having defined a local_var at the class level, when we initially called it within our instance method, the result was “undefined local variable.” Then within the instance method, we defined a local_var, but as the program moved to the class method we again received an “undefined” error.

    Think of scope as apartments in a building, and your keys as local variables. The key that gets you into one apartment is going to work for another apartment.

  • Instance variable (@instance in the earlier example)

    Instance variables are only visible to the object to which they belong. An instance variable initialized in one method definition, inside a particular class, is the same as the instance variable of the same name referred to in other method definitions of the same class.

    In our code above, we defined an instance variable @instance at the class level, and you can see that when we intitially called it, the return was nil. However when we defined @instance within instance method, and called it within the second instance method, we demonstrated that @instance is the same across both instance methods of the same class. We’ve established that the @instance’s scope encompasses both the class and the instance method.

    Then jumping back to the class level, via class_method, we can see the @instance that got printed was the original defined at the top class level. Thus, instance variables share scope across instances of the class, but that instance variables do not survive the change in scope from class level to the class instance.

  • Class variable (@@class_var in the earlier example)

    Class variables’ scope is shared between a class and instances of that class, yet is not visible to any other objects. Typically, this means class variables are used to share data between class-method definitions and instance- method definitions.

    To illustrate this, our example shows how definig our class variable @@class_var at the class level, we are then successfully able to call it within the instance method.

    Because @@class_var’s scope is shared vertically, we can reassign its value anywhere, and the change in state will be maintained elsewhere in the program. Therefore, when we call @@class_var again in the second instance method, the new message is printed, and finally when we call it again in the class method. In the final class method, @@class_var didn’t change back to the original class level definition, like we saw with the instance variable @instance.

  • Global variable ($GlobalVar in the earlier example)

    Within a class, global variables offer the same functionality as class variables. What distinguishes a global variable from a class variables is that global variables are visible all over the program, from within a class to instances of the class, to between classes and objects.

Class v. global variables

In the example above, since we’ve only defined one class, there’s no practical dinstinction between how the global variable behaved v. the class variable.

So let’s quickly create a new example, with two distinct classes, to demonstrate how global and class variables differ.

  class Class1
    $GlobeTrotter = "Global variable from class 1."
    p $GlobeTrotter

    @@ClassVariable = "Class variable from class 1."
    p @@ClassVariable
  end

  class Class2
    puts ">> calling Class 2"
    p $GlobeTrotter
    p @@ClassVariable
  end

  c1 = Class1.new
  c2 = Class2.new

  #=> "Global variable from class 1."
  #=> "Class variable from class 1."
  #=> ">> calling Class 2"
  #=> "Global variable from class 1."
  #=> uninitialized class variable @@ClassVariable in Class2 (NameError)

There you have it. We’ve explored bit how scope differs between the four kinds of variables in Ruby. Even though these concepts are quite basic, in my experience as a developer so far, I haven’t had many opportunities to use class and global variables (whereas local and instance variables are quite common, particularly in Rails apps), so it’s been a helpful exercise in getting it all properly sorted in my head :)

Would love your feedback, and I’d welcome any thoughts or clarifications in the comments below. Would love your feedback, and I’d welcome any thoughts or clarifications in the comments below. Jk. I don’t have comments enabled why don’t you tweet at me!

JavaScript Closures

Closures in JavaScript

What are JavaScript closures?

A closure is a kind of object that combines two things:

  1. a function
  2. that function’s environment

The function’s environment consists of any local variables that were in-scope at the time that the closure was created.

How do you create a closure in JavaScript?

Simply, in JavaScript, if you use the function keyword inside another function, you are creating a closure.

As such, local variables remain accessible after returning from the function you called; the inner function still has access to the outer function’s variables even after the outer function has returned.

Here’s an example of a simple closure in JavaScript:

<script>

var sayHello = function alertGreeting(name){
    var greeting = "Hello";
    function displayName() {
        alert(greeting + " " + name);
    };
    displayName();
};

sayHello("Chris");

</script>

Sample the code on JS Fiddle

There’s a lot, lot more on closures but I just wanted to get the basic definition down. If you want to go deeper, here are a few resources to get you started.

The Difference Between Procs, Blocks and Lambdas

What are Procs and lambdas: Closure in Ruby

First: What is a closure? (Somehow my English degree didn’t teach me this :)

Closures allow declarative programming languages – specifically, languages that do not normally maintain state – to persist data.

They are found in many popular languages including

    * JavaScript 
    * Ruby 
    * Python 
    * C# and 
    * Objective-C.

In Ruby, every Proc object is a closure, which means that each code block you write captures references to data from its surrounding scope for later use. (Source). The core properties of closures, and by extension Ruby procs and lambdas, are:

  1. You can pass Procs and lambdas around like objects (to be called later).

  2. Procs and lambdas remember the values of all the variables that were in scope when the function was created. Procs and lambdas are then able to access those variables when they’re called even if those variables are no longer be in scope.

Let’s dive into some code to examine scope vis a vis procs and lambdas:

    def proc_can_see_outer_scope_locals
      y = 10
        lambda { p defined?(y) }.call
    end

    proc_can_see_outer_scope_locals #=> "local-variable"

    def proc_can_modify_outer_scope_locals
      y = 10
      lambda { y = 20 }.call
      p y
    end

    proc_can_modify_outer_scope_locals #=> 20

    def proc_destroys_block_local_vars_on_exit
      lambda { y = 10 }.call
      p defined?(y)
    end

    proc_destroys_block_local_vars_on_exit #=> nil

    # Code snippet courtesy of the Practicing Rubyist.

For the record, Procs can be executed 3 ways.

    # 1 call method
    puts Proc.new{|x|"blah1"*x}.call(2)

    # 2 array syntax
    puts Proc.new{|x|"blah1"*x}[2]

    # 3 dot syntax
    puts Proc.new{|x|"blah1"*x}.(2)

What are the differences between Procs and lambdas?

Procs and lambdas behave differently upon being returned. As soon as procs are returned, they will escape the function.

For example, if you call return within a method, as soon as the proc hits the method is escaped and that value is returned. Nothing after the initial return will be called.

    def my_method
      puts "before proc"
      my_proc = Proc.new do
        puts "inside proc"
        return
      end
      my_proc.call
      puts "after proc"
    end

    my_method

    #=> before proc
    #=> inside proc

    # code snippets courtesy of Alan Skorks.

The final puts in the method was never executed because the return within my_proc.call dumped us out of the method.

Whereas a lambda will let the function continue after the return value, until the whole function has been run.

    def my_method
      puts "before proc"
      my_proc = lambda do
        puts "inside proc"
        return
      end
      my_proc.call
      puts "after proc"
    end

    my_method

    #=> before proc
    #=> inside proc
    #=> after proc

Possible downside with lambdas is that they can leak memory. This happens when local variables, which would normally be garbage collected by Ruby’s native gc, are instead persisted by lambda’s reference to them.

Resources for further reading:

  1. Skorks on Closures, and Skorks on Procs and lambdas.
  2. Practicing Ruby
  3. JavaScript 101 is garbaggio #=> find something better.

Open Source: How to Git Started

Look, Contributing to Open Source is Super EZ

There are loads of ways to contribute to your favorite open source projects. I list out a bunch of them below.

I’ll also discuss how I ate my own dog food, mostly because I love using that expression. Altho I was actually pretty excited to submit my first open source pull request.


Gitting started.

Working on any open source project on GitHub is just as easy as working on your own team projects. If you know how to use GitHub, you know how to contribute to open source.

Take Ruby, for example. To paraphrase the rubyist Mike Perham (who you probs don’t read but definitely should), Ruby Core has made contributing as simple as:

  1. Fork the Ruby repohttp://github.com/ruby/ruby
  2. Commit changes to your repo — e.g. https://github.com/chhhris/ruby
  3. Submit a pull request – GitHub has a great primer at https://help.github.com/articles/using-pull-requests

Ways to contribute.

I think it’s fairly common knowledge that you don’t have to be a prodigy to contribute to meaningful open source projects. And that’s especially true because there are so many ways to contribute.

I’ve adapted Andy Lester’s post on Smart Bear to list some easy, helpful ways to get involved with Ruby.

Stay informed

  • Join a mailing list

Ruby Weekly produces a very informative and engaging weekly newsletter – sign up at http://rubyweekly.com/. RubyMeetup The official mailing lists are maintained here – http://www.ruby-lang.org/en/community/mailing-lists/

  • Join a user group

Ruby has a dedicated Meetup.com page. RubyMeetup

  • Follow dedicated blogs

There are several active, dedicated Ruby blogs. Ruby Source is a particularly good one – http://rubysource.com/ RubyMeetup

  • Join an IRC channel

IRC is confusing at first glance so I’ll have to spend some more time looking into it. RubyMeetup

Review open tickets

  • Troubleshoot and add detail to open bugs
  • Close old bugs that have been fixed

You’ll need an account in order to review, edit and submit bug reports: https://bugs.ruby-lang.org/projects/ruby/wiki/HowtoReport RubyMeetup

Code

  • Test a beta or release candidate
  • Fix a bug
  • Write a test

Contribute to the community

  • Improve Documentation
  • Answer a question
  • Improve the project website

Let’s do it.

This last idea – improving the project website – is where I ended up getting my foot in the door. I was perusing Ruby’s official website and found a couple links to resources on del.icio.us that had, well, gone stale.

My first step was to locate the source code for Ruby’s official website. After a few minutes scouring the main Ruby repo in vain, I discovered that the project website is, logically, maintained on a separate repo: https://github.com/ruby/www.ruby-lang.org/.

RubyMeetup

Before making any edits, I went to the project’s Readme file for any instructions. First thing was a link to a Wiki page entitled “Guidelines for Contributors.”

The guidelines were very clear and straightforward. Basically, the Ruby-Lang site is built on Jekyll and they suggest most edits/contributions/etc be made as edits directly on the GitHub hosted page (as opposed to cloning the repo, making changes locally, and pushing back to the remote).

RubyMeetup

The project owners had specific instructions for how you should describe your work when submitting the pull request. Bottom line, they ask you to be crystal clear about 1) what page you’re working on, and 2) which language version (as the site is maintained in many languages around the world).

The body text is optional.

RubyMeetup

And that’s it! Even though it was such a minor contribution on a relatively obscure page, the main objective for me was to de-mystify and better understand the logistics for submitting to an open source project. And I’m so glad I did, because it’s a lot simpler than I imagined!

Below is a screenshot of pending pull requests for the ruby-lang.org website. You can see yours truly at the top of the list ;)

RubyMeetup

</end>

Postscript:

A couple hours after I submitted the pull request I heard back from a couple team members..

RubyMeetup

Infographic on Deploying to Production

Infographic: From Development to Production

We had an awesome guest lecture from Spike Grobstein today on deploying from development to a live, production server on Digital Ocean.

Spike was kind enough to provide written instructions that were both thorough and crystal clear.

After a long few weeks of boot camp I decided to give my left brain a rest, let my right brain go to town, and memorialize Spike’s lecture in this infographic.

Infographic

Ruby Reference Tables

Couple of tables worth referencing.

(At least until I know it like the back of my hand.)


Example variable, class and constant names.

Figure 2 - How arrays are indexed.

Sinatra Is Having a Moment

Sinatra is having a moment.

Frank Sinatra is balling out, but the ancient crooner has no idea why.


Seriously, though. What is it about Sinatra?

  • Sinatra is small and flexible. If you’re not trying to build Basecamp who needs all the overhead!?

  • Doesn’t follow the MVC pattern (MVC is so late 20th century).

  • Who’s on it? Oh, I don’t know… Apple, LinkedIn, Heroku, GitHub, the (entire!?) British Government, the list goes on. (via Wikipedia).)

  • Sinatra is a featherweight at a svelte <2,000 lines of code vs. the heavyweight champion Rails at ~100,000 lines of code.

  • Inventor hoedown: in the rails corner, DHH ‘04 vs. Sinatra maven Blake Mizerany ‘07.



Sinatra official imagery


Sinatra is great for the micro-style, Rails is not. As long as you stay micro, Sinatra will beat Rails. If you go beyond micro, Rails will beat Sinatra.



If your app has 5-10 end points, there’s a real benefit to just rolling your own with Sinatra. Essentially if your entire controller structure can fit in a page or two of code, running it in a single file is great.



A large part of Rails’ success is by giving people a curated selection of the best technologies (“best” defined by me and the Rails community). I change Rails every week to better fit what I’d want the perfect framework to be.

DHH on Sinatra vs. Rails (via RubySource)


Below is a bunch of crap that I plan to revisit when I myself have a moment.

First thing’s first, let’s examine how Sinatra apps are packed.

Example i. Tilt


What is Tilt? Tilt is a thin interface over a bunch of different Ruby template engines in an attempt to make their usage as generic possible.

This is useful for web frameworks, static site generators, and other systems that support multiple template engines but don’t want to code for each of them individually.

Packing structure

/bin/ tilt /docs/ TEMPLATES.md /docs/ common.css

/lib/tilt/ #template implementation files in .rb e.g. nokogiri.rb, less.rb, haml.rb, coffee.rb /lib/tilt/ tilt.rb # module w. classes and mapping implementations

/test/ #testing files in .rb e.g. tilt_lesstemplate_test.less, test_helper.rb, tilt_cache_test.rb, et al. /test

autotest .gitignore .travis.yml CHANGELOG.md .COPYING Gemfile HACKING README.md Rakefile tilt.gemspec


Example ii. Brochure

What is Brochure? Brochure is a Rack application for serving static sites with ERB templates (or any of the many template languages supported by Tilt).

It’s the good parts of PHP wrapped up in a little Ruby package — perfect for serving the marketing site for your Rails app.

Folder Structure

lib/ test/ .gitignore Gemfile LICENSE README.md Rakefile brochure.gemspec config.ru.example

Pithy wrap-up goes here.

Functional Programming and Ruby

<<<<<<< HEAD

> Functional Ruby

=======

Functional Ruby

Update

Functional Programming (“FP”) wasn’t on my radar until I started hacking at The Flatiron School two weeks ago (and by hacking I mean as in a hacking cough :).

Since my ego is super attracted to highbrow challenges and feeling intellectually superior, when I heard that FP was baller status because it’s both exceedingly powerful and exceedingly difficult to master, my interest was piqued. When I saw this speakerdeck presentation from Pat Shaughnessy ((“Get yo ass down to O’Shag Hennessy!” “Who?” “O’Shag Hennessy!!” “Principal O’Shaughnessy???”)) analyzing Ruby’s relationship to FP I was like, “challah!”

And here it is:

<<<<<<< HEAD

Say, what is functional programming anyway?

  • Higher order functions, bro.

  • LAZY evaluation (definition: Lazy evaluation delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations. )

  • Memoization (definition: Memoization is an optimization technique used primarily to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs.)

An email from Matz! =>

  • Check out this screenshot of an old-school email from Matz.
  • Why aren’t we calling Ruby “MatzLisp”?!

Screenshot of email from Matz explaining how he invented Ruby

Ruby, and in particular Ruby 2.0, has a lot of functional features. However…

  • Ruby and Haskell can resemble each other, but only on the surface.

Screenshot comparing Haskell and Ruby functions

  • Under the hood, Ruby’s support of functional features is limited.

Slide comparing Ruby and Haskell code

  • Close, but no cigar!

Next slide showing the Ruby code resulting in NoMethodError

In Conclusion

  • Learning a truly functional programming language won’t be trivial.

======= You probably read the deck, but if you didn’t, here are a few takeaways from it.

Amaaazing :-D !

But I’m still confused :–/ ?

One of the coolest factoids is a screenshot of an old-school email from Matz to another developer explaining that Ruby might best be thought of MatzLisp.

Update