Learning to code at Flatiron School

How to Use Custom Data With Highcharts in Your Rails App

Highcharts is a great tool for adding charts to your Rails application. Naturally, there is a very helpful Railscast on the topic, but I wanted to outline another example of using dynamic data to produce a chart.

For our app, OpenExam, we wanted a simple bar graph to display the distribution of quiz scores.

The examples on Highchart’s website all contain hard coded data, but what we needed was a way for Highcharts to take in dynamic data. Following the Railscast as our guide, our code initally looked like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(function () {
  new Highcharts.Chart({
    chart: { renderTo: 'quiz_chart',
             type: 'column'
     },
    title: { text: 'Quiz Distribution' },
    xAxis: { type: 'Percent Correct' },
    yAxis: {
      title: { text: 'Number of Students'}
    },
    series: [{
      data: [1, 2, 5, 7, 3]
    }]
  });
});

Plugging this into jsfiddle, gave us a chart like this.

The formatting looks ok, but data is still static. Ultimately we want to give the Highcharts function two pieces of data to chart out; a correct percentage and the number of students who scored that percentage. The Highcharts documentation shows us that data can be passed in as an array, so now all we need to do is create that array from our data.

First, we created a new method that retrieves the score for each user who has taken a quiz and returns it as an array. In our app, each user’s quiz responses are stored in a user_quizzes table, that knows whether the response is correct or not.

1
2
3
  def self.student_correct_percent_by_quiz(quiz)
    quiz.user_quizzes.where(:status => "Completed").map { |quiz|  (quiz.num_correct.to_f / quiz.total_questions.to_f)*100 }
  end

Now that we have an array of every user’s correct percentage (their grade on the quiz), we want to count the number of users who got the same percentage correct. To do so, we created a empty hash and then iterated through our array counting the number of times the same percentage occurred.

1
2
3
<% scores_top = QuizGrader.student_correct_percent_by_quiz(@quiz) %>
<% count = Hash.new(0) %>
<% scores_top.each {|v| count[v]+=1} %>

This left us with a count hash, that we can easily turn into an array in a format that Highcharts likes : count.to_a.inspect. Plugging that into our Highcharts javascript gives us

and the corresponding chart

How Params Works in Rails

As a Rails beginner, I found it hard to understand what params is all about. Apparently, I am not alone. RailsGuides does a good job of laying out the basics, but going through another example is always helpful.

As you might have guessed, params is an alias for the paramaters method. params comes from ActionController::Base, which is accessed by your application via ApplicationController. Specifically, params refers to the parameters being passed to the controller via a GET or POST request.

In a GET request, params get passed to the controller from the URL in the user’s browser. For example, if our app’s controller looked like

1
2
3
 def show
    @person = Person.find(params[:name])
 end

and the user typed in:

1
http://example.com/person/avi

then the controller would pass in {:name => "avi"} to the show method, which would set the @person instance variable to the person in the database with the name “avi”.

In a POST request, params will get passed to the controller usually from a form. For example, say our app’s controller looked like

1
2
3
def create
  @user = Person.new(params[:person])
end

and our form looked like

1
2
3
4
5
<%= form_for(@person) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :email %>
  <%= f.text_field :email %>

If the user submitted the form with the name “avi” and the email address “avi@example.com” the controller would pass the hash :person => { :name => "Avi", :email => "avi@example.com"} to the create method. Here, @person = Person.new(params[:person]) will become @person = Person.new(name: "Avi", email: "avi@example.com")

Using params gets a bit more complicated when working with nested attributes. Take the example of a playlist app, where a playlist has_many songs and accepts_nested_attributes for songs.

1
2
3
4
5
6
class Playlist < ActiveRecord::Base
  attr_accessible :name, :songs_attributes

  has_many :songs
  accepts_nested_attributes_for :songs
end

Here, the params for a playlist will be a nested hash and may look like this after adding a few tracks:

1
2
3
4
5
6
7
params = { :playlist => {
 :name => 'pop' , :song_attributes => [
  { :artist => 'Michael Jackson', :track => 'Thriller'},
  { :artist => 'Stevie Wonder' , :track => 'Superstition'},
  { :artist => 'U2', :track => 'Beautiful Day'}
  ]
}}

Now, if we wanted to access the track name for the U2 song, the params would look like this:

1
params["playlist"]["song_attributes"][2]["track"] = "Beautiful Day"

Hopefully these examples help to clarify what is often a tricky concept for beginner rails programmers.

Getting Started With Ruby by @danielmorrison Is a Great Intro to Ruby

One of our assignments this weekend was to find a Ruby presentation on Speaker Deck and review it for a blog post. I wanted to find a good intro to Ruby and Daniel Morrison’s “Getting Started with Ruby” was perfect. Note, I’m only reviewing the slides, not the actual live presentation.

The slide show did a great job of going through all the Ruby basics, from Data Types and Strings to Methods and Variables. Each topic got its own slide that included an explanation as well as an example. As you can see below, the slide on Arrays showed how to create one and a few examples of how they can be manipulated.

He even tried to tackle Regular Expressions. Though I thought his explanation was far to cursory to really teach a n00b about regular expressions, I had to remind myself that this was after all just an intro presentation.

I did like how the next slide featured the awesome regular expression tool, Rubular.

He finished up the deck by introducing Ruby on Rails, showing an example of parsing JSON, and a few slides on debugging. Overall this was a great intro to Ruby presenation, even without any audio accompaniment. I wish I could see Daniel give it live, as I’m sure it would rock.

Setting Up a Custom Domain for Your Heroku Octopress Blog

After successfully creating my octopress blog on heroku, it was clear that after-delight-18323 or whatever I was assigned by heroku was not going to cut it. I had registered mentalprolapse.com on Godaddy a couple years back, but had not ever used it. The instructions on Heroku are not the easiest to follow, especially if your domain is registered with Godaddy. Below is the way I was able to do it…

First, go to the Heroku dashboard for your app and locate the Domains section. Add the domain(s) you want to use. Here, I added both www.mentalprolapse.com and mentalprolapse.com.

Next, you have to change the domain name DNS settings at godaddy (or wherever your domain is registered). Since I had my domain parked with Sedo, I had to first change the Nameservers to “I have a hosting account with these domains.” Otherwise, Godaddy will not let you adjust the DNS settings. It should look like this:

Lastly, you have to go into the DNS manager. From here, delete all the existing hosts listed under A(Host), CNAME(Alias), MX(Mail Exchanger), TXT(Text), SRV(Service), and AAAA(IPv6 Host). You can leave the hosts under NS(Nameserver) how they are. Next, use the “Quick Add” button under CNAME(Alias) and put “www” under Host and “proxy.heroku.com” under Points to then click Save Zone File. It should now look like this:

If you have made these changes correctly, your custom domain should resolve to your octopress blog! Note that it may take a couple hours for changes to take effect.

First Post

This is my first attempt at creating an octopress blog. At first I had trouble with the RedCloth gem, but another student found a fix. All I had to do was run

1
ln -s /usr/bin/gcc /usr/bin/gcc-4.2

and then

1
bundle install

and the RedCloth gem was sucessfully installed.