Plain Text Popular Movie Titles List – 1990-2015

I’m not sure if anyone will find this movie titles list useful, but I put together a plain text file of the top 100 grossing movies from each year from 1990-2015. The format of each line in the file is

YYYY\tTitle

I created this list to help me solve a Games magazine puzzle involving movie titles and actors in the said movies.

Here’s the file. Enjoy! 1990-2015 movie titles

Getting started with the MEAN stack and Mean.io – Part 1

If you haven’t heard about it, the MEAN stack consists of:

  • mongoDB
  • ExpressJS
  • AngularJS, and
  • Node.js

The installation and set up process is described in a bunch of
places on the Web. I struggled through it, despite the supposedly
easy process.

I wish I had taken better notes on my initial set up troubles, but I’ll
have to begin by documenting my current state. I think I’ve finally
installed and set up my stack, and (based mostly on the guidance
provided in the mean.io tutoral) I’ve run grunt to start the server.

When I go to http://localhost:5858, however, I get this:

Type: connect
V8-Version: 3.14.5.9
Protocol-Version: 1
Embedding-Host: node v0.10.33
Content-Length: 0

What’s that? I thought it might be some debugging information
that would appear at the bottom of a page, but where’s the page?

In addition to installing the mean stack using the mean.io tools,
I am following the tutorial at thinkster.io, so I’ve created an index.html
and an app.js file. The server is definitely picking them up because it
was giving me some jshint error messages concerning the app.js file
(not using ‘use strict’). I am not, however, seeing anything from the
index.html file.

I have tried to search on the strings in the ostensible debugging info,
but I am coming up empty. Did I neglect to install something?

Maybe the grunt  command doesn’t start MongoDB and maybe
I have to have the DB running? I tried to start Mongo by running
“mongod” at the command line, but I got an error:

exception in initAndListen: 10310 Unable to lock file: /data/db/mongod.lock. Is a mongod instance already running?, terminating

A popular StackOverflow answer says the following command will solve this:

sudo chown -R `id -u` /data/db

That didn’t help though. I had already set the proper permissions on that directory.

Then I tried just checking to see if mongo was already running. I know I tried
this before but I must have just spaced out when I tried it. So I ran this:

ps ax | grep mongod

and killed the process called “mongodb”. Then I started it back up, and successfully viewed localhost:3000.

What I saw on my local server, however, was basically just a big advertisement
for the MEAN stack. Where was this page coming from? It certainly isn’t the
index.html file I had created in the tutorial.

Ok … I found it. The page, which looks like this:

mean.io default home page

This index.html file for this page is located here on my system:

[my mean project root path]/packages/system/public/views/index.html

I think I’m going to stop here for now. I feel like I’ve accomplished something
anyway. I have the server running, the db running, and I have at least a rough
idea of where the files are that I need to edit.

Rails Tutorial Part 2: Setting Up a Server on Heroku for Free!

Continuing from my previous post, in part two of this Rails Tutorial I am going to continue to add to my nascent project. The theme of the project is getting set up on heroku with lots of cool addons … for FREE!.

In part two we will be adding, as promised:

  • Papertrail: an awesome log management service (free)
  • New Relic: Site monitoring (free)
  • PG Backups: postgres backup (free)

Like most heroku add-ons, adding Papertrail was a piece of cake. Just go to the Papertrail add-on page and choose the “Choklad” (i.e. FREE) option. Done.

I add New Relic by simply going to https://addons.heroku.com/ and selecting the either the ‘Stark’ or ‘Wayne’ free version. (I’m not sure which one will better suit my needs, but I’ll go with the one that offers more features for now. I can always switch to another configuration later.)

When I went to verify that everything was connecting, however, I only received a generic message saying “Welcome, ! Thanks for taking advantage of our partnership with heroku.” For some reason it’s not clicking.

Turns out my server was not running correctly. Fortunately, Papertrail helped me track down the source of the issue: My app was not connecting to the Postgres DB successfully. The error message was “FATAL: password authentication failed for user “zapetulgfrdywm” (PG::Error).”

StackOverflow to the rescue, of course. I had to “promote” my heroku DB – I guess it was trying to use the credentials from my local DB. Once I did that the errors went away and my server was up and running successfully.

At this point I went back to New Relic to see if it was starting to show any monitoring information. It wasn’t. Solution: Fortunately it was simple. I just restarted heroku

heroku restart

Not much to show so far, of course, but it looks like it’s running. Yay!

Finally, I’d like to add PG Backups to make regular, automatic (and FREE) backups of my DB. To add it, just go to the PG Backups page and choose one of the three options: “Auto – One Month Retention,” “Auto – One Week Retention,” or “Plus.” I must admit I don’t really understand the differences between the options. The “Plus” option seems geared toward people who want to only do manual backups, but the two “Auto” options seem pretty similar. Maybe the One Month Retention option seems superior. That’s the one I chose anyway. Maybe I’ll discover something preferable about the One Week Retention option later.

Looks like I’m ready to start coding! More specifically, I’m ready for part 3: Getting users authenticated so they can eventually create content for my site.

Rails Tutorial: Setting Up a Server on Heroku for Free!

In this Rails tutorial I am going to set up dev, stage, and production environments. Dev will be on my local machine and I’ll use heroku for stage and production. I’m going to use Unicorn to provide a performance boost and I’ll use postgres as my DB because that’s what heroku will allow me to use.

Why use Unicorn, you may ask. I’m no expert on servers and performance, so I’ll let this quote speak for itself (from “More concurrency on a single Heroku dyno with the new Celadon Cedar stack” by Michael van Rooijen. Read it!).

In any case, what’s important to understand for now is the fact that there’s a master process which loads in your application’s environment, and forks off child processes to serve your application.

The first step to set up my site is to create my local (dev) environment with the basic rails new [app_name] from my command line. [Note that you may want to run rails new [app_name] -d postgresql instead. I haven’t tried it yet but it may save some steps described below.

Next I create my git repository on Bitbucket. The process is terribly simple. Just go to Bitbucket.com, click “Create a repository,” then follow their very clear instructions for adding and committing your source files to your new repo.

After I commit my files, I set up unicorn. I follow the simple instructions in the blog entry “Deploying Rails Applications With Unicorn” and, after running foreman start at the command line, I now have Unicorn running smoothly locally.

Heroku doesn’t like the default db, sqlite, so I followed the instructions in the ASCIICast version of Railscast #342 so I can use postgresql instead. I then edit my ‘database.yml’ file as instructed in the Railscast and StackOverflow thread. When I try to run rake db:create:all, however, I get an error saying I need to run gem install activerecord-postgresql-adapter. So I do. I also change  gem ‘sqlite3’ to  gem ‘pg’ in my Gemfile. Now when I run rake db:create:all, all is good.

Note that in previous attempts to set up my environment, I have run into the same problem as the Railscast commenter “blackpond” – my environment was still using the old version of postgres that cam installed on my mac. Fortunately user “aharte” had the suggestion that worked:

Edit /etc/paths and make sure /usr/local/bin is above /usr/bin in the file. Open a new shell, and you’re good to go!

When I try to push to heroku, however, it complains that I am still using sqlite. I didn’t add my Gemfile to the repo! Simply do a normal git add . followed by git commit -m “[message], then push to heroku with git push staging master and we’re good to go.

Well, not quite. After changing /etc/paths I was getting a “role does not exist” error. This StackOverflow thread recommended that I remove ‘username’ line for my stage and production servers in my database.yml file. It worked!

Now to hook everything up with heroku. I carefully followed the instructions on the Managing Multiple Environments for an App how-to page on heroku.com. This set up my staging and production servers.

Now if I run git push stage master everything processes correctly on the heroku side of things for my stage environment. When things look good on stage, I can just run git push stage production. Woo-hoo!

In the next part of this series, I’m going to add a few add-ons to my heroku set up:

  • Papertrail: an awesome log management service (free)
  • PG Backups: postgres backup (free)
  • New Relic: Site monitoring (free)

Definitely a theme going on here: FREE! If the site gets rolling, hopefully I’ll need to upgrade things, but for now my set up definitely works fine.

Ruby on Rails Cheat Sheet Part 2 – More Tips and Reminders

I am still finding new Ruby and Ruby on Rails tricks (and I keep forgetting them) so I am starting a second Ruby on Rails cheat sheet to help me remember how to accomplish simple tasks.

Check out my first Ruby on Rails cheat sheet if you’re interested. It’s based on the Ruby on Rails Tutorial by Michael Hartl.

Set up a new Heroku app:

heroku apps:create app-name

Push git repo to new Heroku app:

git push heroku master

Reset a postgres DB on Heroku:

heroku pg:reset postgres

View Heroku logs:

heroku logs

Restart Heroku server:

heroku restart

Migrate DB on Heroku server:

heroku run rake db:migrate

Generate a resource without controller actions and without a view

rails g resource resource_name {space-delimited property names}

 

 

Ruby on Rails Tutorial: Creating a Rails Instance from an Existing MySQL DB

In this Ruby on Rails tutorial, I will show how to create a Rails instance from an existing MySQL database.

I have an existing site that used Codeigniter and a MySQL DB, and I want to more or less convert that site into a Ruby on Rails site. I would like to make things as automatic as possible so I don’t have to manually port any of the existing data or create the model properties.

I found this thread on ruby-forum.com that explains the basics of how to migrate an existing MySQL DB so it works with Rails. Let’s follow the steps provided:

1. Write config/database.yml to reference your database.
I’m going to follow the guidelines in the RailsGuides for configuring a MySQL DB. The guidelines say that I should change my config/database.yml file to look something like this:

development:
  adapter: mysql2
  encoding: utf8
  database: blog_development
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

With some small tweaks to match my local environment, I’m ready for step 2:

2. Run “rake db:schema:dump” to generate db/schema.rb.
First stumbling block. I get the following error upon trying “rake db:schema:dump”:
Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter` (mysql2 is not part of the bundle. Add it to Gemfile.)

After following the suggestions I’ve been given (1. gem install activerecord-mysql2-adapter and 2. Adding “gem ‘mysql2′” to my Gemfile) I try “rake db:schema:dump” again.

Second stumbling block. I get this error:
Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)

This StackOverflow thread tells me that I need to figure out the correct socket file and specify it in my database.yml file. I run ‘mysqladmin variables | grep socket’ from the command line and find out that my socket file is located at ‘/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock’ because, of course, I’m running XAMPP for my MySQL server.

Success! Well, I think so anyway. At least I didn’t get any error messages this time.

3. Convert schema.rb into db/migrate/001_create_database.rb
My schema.rb file reflects a successful connection to my MySQL DB. It seemingly faithfully describes the tables and fields of my DB. So I create a ‘/db/migrate’ folder, copy my ‘schema.rb’ file into it, rename it ‘001_create_database.rb’ and wrap the schema as suggested by the ruby-forums.com thread:

class CreateDatabase < ActiveRecord::Migration
  def self.up
    # insert schema.rb here
  end

  def self.down
    # drop all the tables if you really need
    # to support migration back to version 0
  end
end

One note about this: The instructions in the ruby-forums.com thread say the first line of the migration file should be:

class CreateMigration < ActiveRecord::Migration

But it didn’t work for me until I changed it to:

class CreateDatabase < ActiveRecord::Migration

(Note the updated class name.) All good now.

So now I think I have what I need to create the DB if I need to.

Now for the cool part. If I create a simple model whose class name matches one of the tables in my DB, I can immediately start accessing the data in the DB. Simple model:

class Tweet < ActiveRecord::Base
  # I have a table called 'tweets' in the DB
end

Now in the Rails console I can type:

> i = Tweet.find(296) # 296 is an ID of an item in the DB

And I get the data related to that record!

One last thing to really show that a connection has actually been made to the old DB. I want to display some records in the browser. There are really only three steps to accomplish this, but I’ll add a fourth step to allow for pagination between all the records.

Step 1: Add routes to set up basic CRUD functions
This is pretty simple, just add the following line to the beginning of the routes.rb file:

resources :tweets   # replace 'tweet' with the name of your model

Now if I go to http://0.0.0.0:3000/tweets I get an error “uninitialized constant TweetsController.” That’s because, well, I haven’t created my Tweets controller.

Step 2: Add a controller and define an index function
In the ‘/app/controllers’ directory, I simply created a file called ‘tweets_controller.rb’ and added the following text (replacing the names of the classes and models as necessary):

class TweetsController < ApplicationController
 def index
    @tweets = Tweet.paginate(page: params[:page], :per_page => 10)
 end
end

This won’t work until we get through step 3.

Step 3: Add the ‘will_paginate’ gem
In the Gemfile, add the following line:

gem 'will_paginate', '3.0.3'

Then run ‘bundle install’

Step 4: Create a view
In the ‘/app/views’ directory I created a ‘tweets’ directory and within that directory I created a file called ‘index.html.erb’. The ‘index’ part of that file name matches the index function of my TweetsController for a reason – this view gets called automatically when the user goes to ‘/tweets/index.html’.

In the same ‘/app/views/tweets/’ directory I create a very simple partial file that will be called whenever an individual tweet needs to be displayed. That file is called “_tweet.html.erb” and the contents look like this:

<li>
  <!-- tweet_text is a field in the tweets table -->
  <%= tweet.tweet_text %> 
</li>

The contents of the ‘/app/views/tweets/index.html.erb’ file I mentioned above look like this:

<%= will_paginate %>
 <ul class="users">  <!-- Knows to repeatedly render the _tweets partial -->  <%= render @tweets %>  </ul> <%= will_paginate %>

And that’s it! I get all my DB records listed, 10 at a time, with pagination links so I can jump around between them. There’s no formatting and a lot more work will go into displaying and organizing the data, but this is a really good start.

I create these rough tutorials as I go, so I fear some of the info may be disjointed or inconsistent. Please let me know if you have any questions or need anything clarified. I’m happy to help.

Ruby on Rails Cheat Sheet – Handy Tips Gleaned from RoR Tutorial Book

Every time I go away from RoR for a while, I forget everything I had learned. In order to get me up to speed more quickly in the future, I am going to create a Ruby on Rails cheat sheet that describes how to accomplish simple tasks with Rails.

These tips all come from the Ruby on Rails Tutorial by Michael Hartl and the section #s below refer to it (http://ruby.railstutorial.org/book).

Create static pages (3.1.2):

Tell generate to use RSpec:

rails generate rspec:install

Generate static pages:

// generates home and help pages
rails generate controller StaticPages home help --no-test-framework

 Undoing generate commands

// Example
rails generate controller FooBars baz quux
rails destroy  controller FooBars baz quux
// Example 2
$ rails generate model Foo bar:string baz:integer
$ rails destroy model Foo
// Rake db:migrate example
rake db:migrate
rake db:rollback

Everything in Ruby (even a string and nil) is an object (4.2.3)

nil.to_s
=> ""
"foobar".empty?
=> false

 Array operations followed by a bang (!) affect the array (4.3.1)

>> a
=> [42, 8, 17]
>> a.sort
=> [8, 17, 42]
>> a
=> [42, 8, 17]
>> a.sort!
=> [8, 17, 42]
>> a
=> [8, 17, 42]

You can think of symbols as basically strings without all the extra baggage (4.3.3)

>> user = { :name => "Michael Hartl", :email => "a@b.com" }
=> {:name=>"Michael Hartl", :email=>"a@b.com"}
>> user[:name]       # Access the value corresponding to :name.
=> "Michael Hartl"

Alternate syntax for using symbols as hash keys (4.3.3):

>> h1 = { :name => "Michael Hartl", :email => "michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"michael@example.com"}
>> h2 = { name: "Michael Hartl", email: "michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"michael@example.com"} 
>> h1 == h2
=> true

Adding Bootstrap and Sass (5.1.2)

  1. Make sure the bootstrap gem is listed in your gemfile
    gem 'bootstrap-sass', '2.0.4'
  2. Create a Sass file (app/assets/stylesheets/custom.css.scss) with the following line
    @import "bootstrap";
  3. That’s it!

Creating and referencing partials (5.1.3)

  1. File name and location:
    app/views/layouts/_partial_name.html.erb
  2. Reference to partial:
    <%= render 'layouts/partial_name' %>

 Asset directories and their purposes (5.2.1)

  • app/assets: assets specific to the present application
  • lib/assets: assets for libraries written by your dev team
  • vendor/assets: assets from third-party vendors

Each has images, javascripts, and stylesheets subdirectories.

Routes to static pages (5.3.2)

The following line redirects /help to the help.html.erb layout in the static_pages directory

match '/help',    to: 'static_pages#help''

It also creates the following two named routes:

about_path => '/about'
about_url  => 'http://localhost:3000/about'

Creating a controller (5.4.1)

# Creates a simple "new" view and empty "new" controller method
# --no-test-framework prevents creation of initial testing spec
rails generate controller Users new --no-test-framework

Creating a model (6.1.1)

rails generate model User name:string email:string

 Annotating model definitions with details from their DB counterparts (6.1.2)

# Add gem to Gemfile (only for development)
gem 'annotate', '2.5.0', group: :development
# Goes through DB tables and comments corresponding model files
bundle exec annotate

 Test Driven Development (3.2.1, 6.2.1)

  • Create a ‘request’ test for each static page (/spec/requests/…)
  • Create a model test for each model (/spec/models/…)

Adding migrations to an existing model (6.2.5)

rails generate migration add_index_to_users_email

Look for the new migration file and edit it appropriately. Then run:

bundle exec rake db:migrate

Example #2 (specifying a column to add to a table):

rails generate migration add_password_digest_to_users password_digest:string

Post migration creation:

$ bundle exec rake db:migrate
$ bundle exec rake db:test:prepare
$ bundle exec rspec spec/

Also, use add_index (8.2.1) to create an index on any column that will be used to retrieve info

Add debug info to a view (7.1.1)

<%= debug(params) if Rails.env.development? %>

Run console in a different environment (test/development/production) (box 7.1)

rails console test

Run server in a different environment (test/development/production) (box 7.1)

bundle exec rake db:migrate RAILS_ENV=production

Reset the database (7.2)

bundle exec rake db:reset

# "ensures that the data model from the development database is reflected in the test database" 
bundle exec rake db:test:prepare 

[restart Web server]

Completely clear and reset the data base (http://bit.ly/RL1HN1)

rake db:drop
rake db:create
rake db:migrate

Run a subset of rspec tests matching a string (7.4.4)

rspec -e "signup page"

Deploy to Heroku (7.4.4)

1. git push heroku
2. heroku run rake db:migrate
3. heroku open (opens the site in a browser)

Reset a Heroku DB (9.5)

$ git push heroku
$ heroku pg:reset HEROKU_POSTGRESQL_CHARCOAL_URL [probably]
$ heroku run rake db:migrate
$ heroku run rake db:populate

Making error messages more user friendly (7.6)

Flash messages vs. flash.now messages (8.15)

  • flash messages stay on the screen for one request (ex: redirect)
  • flash.now messages for one render. Goes away on next request.

Note about helpers

  • By default, all the helpers are available in the views but not in the controllers
  • So, it is necessary to explicitly include helpers within controllers

Cool shortcut to finding objects by a property (8.2.3 and elsewhere)

Object.find_by_property("str")
ex: User.find_by_name("Joel B")
ex: User.find_by_email("jberghoff@yahoo.com")

 Writing tests for checking cookie values (not a great idea) (8.2.6)

… experience shows that direct tests of cookie values are brittle and have a tendency to rely on implementation details that sometimes change from one Rails release to the next. The result is breaking tests for application code that still works fine. By focusing on high-level functionality—verifying that users can sign in, stay signed in from page to page, and can sign out—we test the core application code without focusing on less important details.

Visiting a typical page with RSpec:

before { sign_in user }

Visiting a path involving an update with RSpec (9.2.1)

before { put user_path(user) }

Note that direct use of the PUT HTTP request here. There’s no other way to do it.

Using exclamation points with actions (9.3.2)

  • create will return “false” if it doesn’t work
  • create! will raise an exception if it fails

Populating the DB with sample users (see section 9.3.2)

Adding a boolean field to a db table = awesome (9.4.1)

1. $ rails generate migration add_admin_to_users admin:boolean
2. Creates
      class AddAdminToUsers < ActiveRecord::Migration
        def change
          add_column :users, :admin, :boolean, default: false
        end
      end
3. Change line to: add_column :users, :admin, :boolean, default: false 4. This automatically creates test user.admin? test

Only attr_accessible attributes can be assigned through mass assignment (9.4.1)

A note about arrays in Ruby (10.1.4)

Array assignment in Ruby copies a reference to the array, not the full array itself, which means that changes to the original array also affect the copy.

A Simple Example – Backbone.js Tutorial Part 2 – Creating an App View

Thanks for checking out part 2 of my Backbone.js tutorial.

In my previous entry I set up a model, a collection, and a view related to a “profile” – essentially bios for the people who work with me at Fortified Studio. The collection grabbed some JSON, used that data to create corresponding models, then displayed the data in a view. I’m still not sure I’m doing things in the best backbone.js way, but it’s working and I don’t think I’m doing anything outrageously against the rules.

Ultimately though, my page needs to have several views, each of which grab their data from JSON files. So I’d like to have a master view that render all the sub-views. I can render my profiles view now, then add other views as I build them.

I’ve seen app views created before, but none of them have struck me as the definitive way to do things. I’m sure I’ve tried this before, but I am once again going to look to the todos.js example for some guidance. Their AppView is somewhat lengthy, but I’ll start slowly and see what I can glean from it.

Firstly, I’ll follow the todos.js lead and bind the view to an existing DOM element. In my case I will bind it to the <body> tag. Is there anything wrong with that? Should I be binding it to a tag within the body? I’ll also use the app view’s initialize method to call fetch on the collection of profiles. Here then, is the very simple first iteration of the app view:

var AppView = Backbone.View.extend({
   el: "body",
   initialize: function() {
      profiles.fetch();
   }
});

Simple and it works. Next I’d like to trigger the rendering of subviews within the app view’s render function. Then again, I guess I don’t need to do this because I’ve already bound the rendering of the profiles to the ‘reset’ event triggered by the profiles collection.

How about if I instead insert all profiles-related instantiations into the app view’s initialize method. This doesn’t affect the functionality, but I suppose it cleans things up a bit.

var AppView = Backbone.View.extend({
   el: "body",
   initialize: function() {
      var profiles = new ProfileList(); 
      var profilesView = new ProfileView({
         model: profiles
      });

      // When profiles have been successfully grabbed,
      // display them using profile template
      profiles.bind('reset', function () {
         profilesView.render();
      });

      profiles.fetch();
   }
 });

Now I only instantiate the app view and the rest takes care of itself.

var App = new AppView;

This seems ok for now. Tomorrow I’ll see what happens when I try to add a second, more complicated subview. Here’s the code from today: backbone.blog.2.zip

Here are some handy links to parts 1 and 3 of this tutorial:

A Simple Example – Backbone.js Tutorial Part 1 – Collection based on JSON + View

I still don’t feel like I understand Backbone at all. I decided to scrap what I had previously built – despite the fact that it’s working – because I don’t truly understand why it’s working. The result is this simple example presented as a backbone.js tutorial.

So … starting from nothing. Here we go. It won’t take long before I am completely stuck.

I want to create a simple list of user profiles. The profiles will be brought in via a JSON file and displayed as a list. Seems so simple!

I’ll start by creating the model:

var Profile = Backbone.Model.extend();

I’ve seen it done this way in many examples. Sometimes default values are added, but usually it’s just this simple declaration. According to the backbone.js documentation, it’s also possible to add an initialize function and to add validation. I’m going to keep things as simple as possible for now though.

Next, I know I want a collection of Profiles, so I will create that in its most simple form:

var ProfileList = Backbone.Collection.extend({
   model: Profile
});

That looks to me to be a collection of individual Profiles.

I know I want to generate the models based on the values in an external JSON file. According to backbone.js: “Set the url property (or function) on a collection to reference its location on the server. Models within the collection will use url to construct URLs of their own.” As a result, I have this:

var ProfileList = Backbone.Collection.extend({
   model: Profile,
   url: '/json/profiles.json'
});

Does the collection automatically go out and grab the JSON? I don’t think I should need to explicitly call fetch() because the documentation says: “Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place.” And further: “fetch is intended for lazily-loading models for interfaces that are not needed immediately.” So if I create an instance of ProfileList the models should be created automatically, correct? I’ll try it:

var profiles = new ProfileList();
console.log(profiles);

This results in an empty object. Am I not giving it enough time to grab the JSON? If I could trigger the call to console.log on a “success” event or something similar, that would be a good way to know the collection has grabbed the data.

Changing my code to this produces different results:

var profiles = new ProfileList(); 
profiles.fetch();
console.log(profiles);

But I still think I need to trigger console.log with an event. When I look at the results using Firebug, it still shows me an empty object, but now when I click through to see the empty object in more detail I can see that the data is there. It had showed me more emptiness when I clicked through it before adding the explicit call to fetch().

Here is my attempt to bind the call to console to when the collection grabs the data (note that this at least partially derived from this StackOverflow example):

var profiles = new ProfileList(); 
profiles.fetch();
profiles.bind('reset', function () { console.log(profiles); });

And indeed this works. The backbone.js documentation says I shouldn’t call fetch explicitly on page load though. So how do I get the data without calling fetch()?

I found a StackOverflow thread that addresses this exact issue. The answers are not crystal clear to me though. I think the conclusion is that you can either send in a static reference to an initial set of data, then call fetch() as needed to grab more, or you call fetch explicitly like I am doing.

I suppose I could change my JSON file to create a variable holding all my data, then pass it directly to the collection. That avoids a server call, but it doesn’t seem right. For one thing it will be a little cumbersome to switch to a dynamic data source (e.g. a db) down the line. I guess it just seems less flexible in general.

I’ll stick with explicitly calling fetch() for now.

Now I need to display my data. I need to create a view to display the profiles. The view should use an underscore template I have created and the rendering should be triggered by the ‘reset’ event of the profiles collection. I have a div already on the page and I’d like the newly created DOM elements to be inserted into that div.

The ID of the element into which I want the new DOM elements inserted is “profiles,” so the first line of my view is :

el: "#profiles"

My understanding is that by setting the ‘el’ property I am telling backbone there is an existing DOM element I want to use. If instead I were to set values for “tagName”, “className”, “id” or “attributes” properties, backbone would create a new element with those attributes.

I know that to specify the template to be used by the view I do this:

template: _.template($('#profileTemplate').html()),

Where the template with the id ‘profileTemplate’ looks like this:

<script id="profileTemplate" type="text/template">
   <div class="profile">
      <div class="info">
        <div class="name"><%= name %></div>
        <div class="title"><%= title %></div>
        <div class="background"><%= background %></div>
      </div>
  </div>
</script>

I think my view can have a simple render function that looks like this:

render: function(eventName) {
   _.each(this.model.models, function(profile){
      var profileTemplate = this.template(profile.toJSON());
      $(this.el).append(profileTemplate);
   }, this);

   return this;
}

So the complete view looks like this:

var ProfileView = Backbone.View.extend({
   el: "#profiles",
   template: _.template($('#profileTemplate').html()),
   render: function(eventName) {
      _.each(this.model.models, function(profile){
         var profileTemplate = this.template(profile.toJSON());
         $(this.el).append(profileTemplate);
      }, this);
      return this;
   }
});

Indeed, this works as I had hoped.

Here’s the code from today’s complicated look at a simple backbone application:
backbone.blog.1.zip

Tomorrow I’m going to jump to a slightly more complicated example. I’d also like to incorporate the above code into a more general app view that can handle multiple sub views.

Here are some handy links to parts 2 and 3 of this tutorial:

Dashes (Hyphens) vs. Underscores – Which is better for SEO?

I can’t find a solid answer on this potentially important SEO topic.

The most referenced source seems to be this blog entry from Matt Cutts (a Google employee). That entry, however, is from 2005.

That’s ancient in internet terms. That article advocates for dashes over underscores, but it’s based on rather flimsy data.

There’s a follow-up entry of sorts from August 2007 where Matt seems to say underscores are fine, but dashes are slightly better.

And that’s it. I can’t find any definitive information from either side of the fence since then. That’s over a year and a half ago.

Arguments (from people who have some evidence to back it up, as well as people who are just guessing) on the side of dashes:

  • It looks better.
  • Dashes are used in everyday language (i.e. natural language).
  • Sites with dashes in their URLs show up higher in search results than sites with underscores.

Pros (again, from people who may or may not know better) for underscores:

  • Underscores are not used in everyday language, so they’re a good replacement for spaces.
  • Plenty of sites (Wikipedia, TypePad, etc.) use underscores.
  • Sites with underscores in their URLs show up higher in search results than sites with dashes.

Ugh. Can’t anyone provide a definitive answer? I have sites to build!