b a d p o p c o r n

Can facebook predict if your girlfriend will break up with you?

Written by Moe on May 21, 2009 | No Comments

The Wall Street journal has an interesting article on yet another innovative algorithm Google is working on. Venture beat summed up the article well; “In the wake of recent brain drain, the search giant has devised an algorithm that combines employee reviews, promotion histories, pay and other factors to predict which employees are most likely to leave.” Right after I read this article I found myself on the facebook “Suggestions” page, or as I like to call it, “The People I Don’t Know” page. I came up with ideas and decided to post my notes.

    Location

  • Where you should live. Based on the amount of people you interact with the most and their current locations.
  • Places you should avoid. Do the exact opposite of the logic above.
  • Music, Television, Hobbies etc
  • Display the top among your friends, and sort by the friends you interact with the most.
  • Friendships
  • Facebook needs to clarify why you should be friends with the people they suggest. Breaking the list into categories of; people who share the same type of information as you do, people who join and discuss the same type of topics you do, People who attend the same type of events as you do, and people that have things in common (profile details) as you do.
  • Relationships (for fun)
  • Your girlfriend/boyfriend will most likely break-up-with/cheat on you with “insert name here” in the next three to four weeks.
  • A “you could probably hit it” section.
  • A he’s just not that into you list.
  • The variables I would use to figure out the feelings/attitude person A has towards person B.

    • 1. The difference between the the average number of wall posts(per friend) person A has posted, and the number of wall posts person A has posted on person B’s wall.
    • 2. The difference between the the average time it takes person A to respond to a wall post and the average time it takes person A to post on person B’s wall.
    • 3. The average time person A spends on person B’s profile compared to person A’s average among their friends.
    • 4. Use 1 and 2 but for messages instead of wall posts.
    • 5. Use 1 and 2 but for photos tagged.
    • 6. Use 1 and 2 but compare the results, if possible, to person’s A last’s relationship during the time the relationship was active.
    • 7. Compare wall posts, messages, other activity of current couples, prerelationship, with the current posts, messages and other activity of person A and B.

Posted in Life Stuff

No Comments

Mysql Gem for Ruby Enterprise Edition on Mac OSX

Written by Ben on April 17, 2009 | No Comments

I just recently installed Ruby Enterprise Edition on my Mac, but found the following errors:

ERROR: Error installing mysql:
ERROR: Failed to build gem native extension

The reason was that the Mysql files are installed under version specific directories and files when installing from Macports. For example, mysql5 or /opt/local/lib/mysql5. This messes up the mysql gem installation because it looks elsewhere by default. The solution is to specify the exact mysql config location in the installation process:

bash-3.2# /opt/ruby-enterprise-1.8.6-20090201/bin/ruby \
/opt/ruby-enterprise-1.8.6-20090201/bin/gem install mysql \
— –with-mysql-config=/opt/local/bin/mysql_config5

That last line is two dashes (-) followed by the –with-mysql-config option.

Easy as pie.

Posted in Life Stuff

No Comments

Google Voice, First Impression

Written by Moe on April 10, 2009 | No Comments

Our Grand Central account magically turned into our Google Voice account the other day, and I couldn’t be more pleased. Google took the robust look of Grand Central and made it look as simple as Gmail. I can easily browse call history, send a sms or update our voicemail. I’m really excited to see how well the voicemail transcript will work also, and if it will be offered with recorded calls. The most popular feature might just end up being the call widget; “You can allow others to call you from your website or blog by adding a call widget to it. Visitors to the website can click the widget, enter their phone number, and Google Voice will call them and connect the call to your Google number.”

You can also call out of the country with competitive VOIP rates. Wait a minute…Google might generate a large revenue source other then ads!?

Posted in Life Stuff

No Comments

How to Quickstart Merb Slice Development

Written by Ben on November 2, 2008 | 6 Comments

What are Merb Slices?

Merb Slices are a kind of mini Merb Application that can be packaged up as gems and used as is (or with customizations) within actual Merb Applications. They are full Model-View-Controller stacks to support a large feature within a larger application. Examples could be a full blogging system, user management system or a file upload system.

Where else can I find good overview information about Merb Slices?

There are a few places, but you should start with the MerbCamp 2008 MerbSlices talk by Daniel Neighman aka hassox. His slides are found here and here. Watch the other MerbCamp videos for more Merb info.

So what does this article cover?

This just provides some missing details for a developer to immediately get a slice working. The above material gives a great overview of slices in general and the why/how to use/install them in main Merb applications.

Let’s start by creating our slice.

$ merb-gen slice myslice
Generating with slice generator:
     [ADDED]  app/controllers/application.rb
     [ADDED]  app/controllers/main.rb
     [ADDED]  app/helpers/application_helper.rb
     [ADDED]  app/views/layout/myslice.html.erb
     [ADDED]  app/views/main/index.html.erb
     [ADDED]  config/init.rb
     [ADDED]  config/router.rb
     [ADDED]  lib/myslice.rb
     [ADDED]  Rakefile
     [ADDED]  README
     [ADDED]  spec/myslice_spec.rb
     [ADDED]  spec/controllers/main_spec.rb
     [ADDED]  spec/spec_helper.rb
     [ADDED]  stubs/app/controllers/application.rb
     [ADDED]  stubs/app/controllers/main.rb
     [ADDED]  TODO
     [ADDED]  public/javascripts/master.js
     [ADDED]  public/stylesheets/master.css
     [ADDED]  LICENSE
     [ADDED]  lib/myslice/merbtasks.rb
     [ADDED]  lib/myslice/slicetasks.rb
     [ADDED]  lib/myslice/spectasks.rb
$ cd myslice

Our goal here is to set up our slice so we can actually do development without needing to install it within a Merb application, and to give an example run through of creating a resource.

Let’s start by editing the slice’s init.rb file. This file is solely used in your slice development cycle; it is omitted from the final packaged gem; it is NOT used in production. If you look at the slice’s Rakefile, you will see that NO file in the config/ directory is included in the gem.

$ vi config/init.rb
# Add the following to the top of the slice's config/init.rb file.
# USE THE CORRECT GEM VERSIONS.
merb_gems_version = "0.9.12"
dm_gems_version   = "0.9.6"

# Uncomment the following two lines to develop with haml instead of erb.
# dependency "merb-haml", merb_gems_version
# use_template_engine :haml

dependency "dm-core", dm_gems_version
dependency "dm-aggregates", dm_gems_version
dependency "dm-migrations", dm_gems_version
dependency "dm-timestamps", dm_gems_version
dependency "dm-types", dm_gems_version
dependency "dm-validations", dm_gems_version

use_orm :datamapper

What we did above is to declare a dependency on the DataMapper ORM. You can use whatever ORM you wish, but I’ll be using DataMapper as the example in this article.

Also, I have included commented lines to show how one would use Haml instead of Erb as the templating engine. I highly suggest that developers write views for BOTH Erb and Haml when developing slices. This gives the users of such slices a choice.

Since we’re editing files in the config/ directory, we’ll go ahead and create the database.yml file we’ll need.

$ vi config/database.yml
# This is a sample database file for the DataMapper ORM
development: &defaults
  # These are the settings for repository :default
  adapter:  sqlite3
  database: sample_development.db

Next, we go ahead and try creating a resource as most developers will be doing. It’s just the same merb-gen command as one would do for any regular Merb application.

$ merb-gen resource article
     [ADDED]  spec/models/article_spec.rb
     [ADDED]  app/models/article.rb
     [ADDED]  spec/requests/articles_spec.rb
     [ADDED]  app/controllers/articles.rb
     [ADDED]  app/views/articles/index.html.erb
     [ADDED]  app/views/articles/show.html.erb
     [ADDED]  app/views/articles/edit.html.erb
     [ADDED]  app/views/articles/new.html.erb
     [ADDED]  app/helpers/articles_helper.rb

When we edit the articles controller, we’ll see that it looks exactly like a generated resource that one would get in a Merb application. In fact that’s probably the whole point since we want our slices to be full MVC stacks to implement our subsystem features. But if we tried to use this resource right now, we’ll find that our slice just won’t work. The main reason is how we define a slice’s controller versus a controller in a full Merb application. The whole issue is about namespacing.

$ vi app/controllers/articles.rb

We need to change the following class declaration:

class Articles < Application

to

class Myslice::Articles < Myslice::Application

This article class needs to inherit from the slice’s application class instead of whatever Merb app it is installed in. And the Articles class needs to be in the Myslice namespace so the slice router rules will actually be able to find the class.

The rest of the controller looks good. It’s got all the default DataMapper access code for its methods. NOTE: If one did not call “use_orm :datamapper” in the slice’s init.rb file, then all this ORM access code will be omitted; one would have a plain class whose methods just called `render`.

As a next step, one would generally verify that merb-gen would have updated the config/router.rb file with this new resource. WARNING! The config/router.rb file is NOT where routes are configured for slices. Everything is done in lib/myslice.rb, or whatever it is named in your real slice. In fact, this is also where we’ll find other configuration options.

$ vi lib/myslice.rb

Let’s go ahead and update our slice meta data. Replace the following code with your own stuff.

# All Slice code is expected to be namespaced inside a module
  module Myslice

    # Slice metadata
    self.description = "Myslice is a chunky Merb slice!"
    self.version = "0.0.1"
    self.author = "Engine Yard"

I won’t cover the other slice hooks in this file except for the “def self.setup_router(scope)” method. This is where you SHOULD to add your resource. Although the scope.default_routes line will correctly route to your resource, I find it cleaner to explicitly declare the slice’s routes. Watch the video mentioned above to understand why we setup routes in this hook instead of a slice’s router.rb file.

def self.setup_router(scope)
      # Add the following resource line
      scope.resources :articles
      # The lines that follow are the pre-generated ones.

      scope.match('/index(.:format)').to(:controller => 'main', :action => 'index').name(:index)
      # the slice is mounted at /myslice - note that it comes before default_routes
      scope.match('/').to(:controller => 'main', :action => 'index').name(:home)
      # enable slice-level default routes by default
      scope.default_routes
    end

I personally would delete the “scope.default_routes” line because I’m all about explicitly specifying routes.

At this point, we’ve got routes and a fixed up controller.

Now we look at the Article model. This model contains the code required to define it as a DataMapper resource.

$ cat app/models/article.rb
class Article
  include DataMapper::Resource

  property :id, Serial
end

Again, as with controllers, the DataMapper code would have been omitted without the “use_orm :datamapper” in the slice’s config/init.rb file. We would have had an empty class.

I will skip over how we develop Models for Datamapper in Merb. One should watch the other MerbCamp videos for that. Let’s just assume that you’ve added a few other properties to the Article model class.

Let’s create the model’s sqlite3 tables.

$ rake db:automigrate
Don't know how to build task 'db:automigrate'

Oops. We don’t have that kind of default support in our slice’s rake tasks. But no fear, we’ll just invoke the auto_migrate! directly:

$ echo 'DataMapper.auto_migrate!' | slice -i
Loading init file from /Users/notroot/projects/myslice/config/init.rb
 ~ Connecting to database...
 ~ Loaded slice 'Myslice' ...
 ~ Parent pid: 9145
 ~ Activating slice 'Myslice' ...
DataMapper.auto_migrate!
[Merb::DataMapperSessionStore, Article]

Be sure to use single quotes since the `!’ character is special in bash. But if you want to do it interactively, just start up the slice irb console.

$ slice -i

The only other thing to note is how slice sql tables are named. Our “articles” table in the slice’s development database becomes “myslice_articles” in a Merb application’s database.

And to finally get it all together, we need to start mogrel to serve up the slice… but NOT using the `merb` command. We use the `slice` binary.

$ slice
Loading init file from /Users/notroot/projects/myslice/config/init.rb
 ~ Connecting to database...
 ~ Loaded slice 'Myslice' ...
 ~ Parent pid: 9147
 ~ Activating slice 'Myslice' ...
merb : worker (port 4000) ~ Starting Mongrel at port 4000
merb : worker (port 4000) ~ Successfully bound to port 4000

And off to the browser you go; and off to developing your slice.
Example) http://localhost:4000/articles

So what’s next once I finish developing my slice?

Install your slice directly into your gem repository.

$ sudo rake install

Add your slice to the application’s list of dependencies.

$ cd ~/projects/myapp
$ vi config/dependencies.rb
# Add your slice dependency to the bottom of the file.
dependency "myslice", "0.0.1"

Install the Slice into your Merb Application.

$ rake -T slices
$ rake slices:myslice:install

And go ahead and add your slice to your application’s router.rb file.

$ vi config/router.rb
# Find the following method call and add your slice.
Merb::Router.prepare do
  # This mounts your slice to the default http://example.com/myslice/
  # "namespace". See Merb's rubydocs for more info about options.
  slice(:myslice)

  # other stuff omitted.
end

Now, you can run `merb` to start up mongrel for your application and
hit away under the /myslice url path namespace.

Example) http://localhost:4000/myslice/articles

Go forth and slice!

Posted in Ruby, Technology, Web

6 Comments

Installing Mysql with MacPorts for Rails on Leopard

Written by Moe on September 19, 2008 | 5 Comments

I just spent a hour going through this so you won’t have to. I thought I installed mysql using mac ports but I kept getting this error.

Errno::ENOENT (No such file or directory - /tmp/mysql.sock):

Below are the three steps you need to get Mysql running on Leopard for MacPorts.

sudo port install mysql5 +server
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist
sudo ln -s /opt/local/var/run/mysql5/mysqld.sock /tmp/mysql.sock

Posted in Rails

5 Comments

Authentication and Authorization in Rails

Written by bill on September 16, 2008 | 4 Comments

Some say Rails is “missing” a lot of things you might expect to find in full-featured web development framework, but it doesn’t matter - what’s it’s NOT missing is a plugin system which allows you to add any functionality you need by pulling a few bits of code from other authors into your site. What I’ll be using in this example are the restful-authentication plugin for authentication and the role_requirement plugin for authorization. Both of these are hosted on github, which hosts loads of Rails plugins along with other open projects. As the name implies, they use git for their repositories, so you should install git to grab these plugins.

Setting up authentication

First, you’ll need to set up authentication. In the vendor/plugins folder of your project, run:

git clone git://github.com/technoweenie/restful-authentication.git restful_authentication

This will grab a copy of the restful_authentication plugin; you don’t need to mess with any of the code in the plugin itself. go back to your project’s root and run:

script/generate authenticated user sessions
rake db:migrate

This will set up the user model for you and insert the users table in your database. You can add arguments to the generate script such as –include-activation –aasm to enable activation emails but we’re not going to cover all of that right now.

Now, you’ll have two new controllers in your application, sessions_controller.rb and users_controller.rb. Go to each of these files and remove or comment out the line that says ‘include AuthenticatedSystem’, and copy this line to the top of the application controller instead, right at the beginning of the class definition:

class ApplicationController < ActionController::Base
  include AuthenticatedSystem

and so on. The generate script should have also added these lines to routes.rb:

map.logout '/logout', :controller => 'sessions', :action => 'destroy'
  map.login '/login', :controller => 'sessions', :action => 'new'
  map.register '/register', :controller => 'users', :action => 'create'
  map.signup '/signup', :controller => 'users', :action => 'new'
  map.resources :users

  map.resource :session

These give you some prettier URLs rather than, for example, /users/new to sign up and /sessions/new to login. Generally you want the first thing a user sees to be the login page, so if you want to you can make that the default by adding

map.root :controller => "sessions", :action => "new"

to your routes. You’ll also need to remove or rename index.html in the public folder.

At this point you have a basic authentication system, which is great considering how easy it is to set up, but alone it’s pretty useless. You’ll notice, no matter if you’re logged in or not, you still have full access to your app. So why did we even bother? Because now, you can add authorization to lock down actions based on roles you set up.

Setting up authorization

There are a few different ways to do this; if you want a very, very granular authorization system you can install padlock authorization which allows you to set roles per each object in your application. We decided this was probably overkill for our latest project, but I may touch on it in a later blog if we decide to use it after all. We’ll be using the aforementioned role_requirement plugin.

Back to github with us! Head back to your /vendor/plugins folder and run:

git clone git://github.com/timcharper/role_requirement.git role_requirement

Go back up to your application’s root, and run:

script/generate roles Role User
rake db:migrate

Now, you’ll have to make some manual database changes. You need to add one or more roles to the roles table, and if you have any users, assign them initial roles, if you want them to have roles, in the roles_users table. You can, of course, just add a new controller and view to make all this changeable from your application, but you’ll probably still be setting up one admin user by hand to start things off when you go live.

Now you can go about editing your controllers to make each one accept and reject your roles. For example, say I have a simple model with with a TV show, which can have one starting date. To allow only administrators to make changes, you can set up your Shows controllers like so:

class ShowsController < ApplicationController
  require_role "ADMIN", :for_all_except => [:index, :show]
  def index
    @shows = Show.find(:all)

(The rest is standard Rails boilerplate)

A later post will probably deal with setting/changing roles within your application.

Posted in Rails

4 Comments

What it’s like to work in the game industry

Written by Aaron on September 15, 2008 | 1 Comment

The title is loaded. I can not pretend to know what it is like for everyone in the industry, and I won’t even attempt to give an exhaustive depictions of even my own personal experiences. Trust me you wouldn’t be reading this post now if I had titled it “A rough overview of generally what it’s like to work in the game industry”.

The short answer

GOOD

The long answer

The experience of being in the Peace Corps is commonly described as “The Toughest Job You’ll Ever Love”. I hate that they have dibs on the line because, besides being a great quote, it captures a good bit of the heart of working in the game industry. If you work in the game industry you probably love games and most of the people that you work with do too.

The other people often end up being the best part –Warning– The money will probably never end up being the best part. Not to say that everyone in the industry lives with their parents, just don’t expect golden toilets. Most people in the industry make enough to support themselves, and even their families, just trust me, you’ll be richer in friendship than wealth…unless you’re a complete prick (In which case you’ll probably end up in charge of a game studio and swimming in cash and–if there’s a God–cutting yourself every night as you drink yourself into unconsciousness wondering what is wrong with everyone else that makes them not like you).

Yeah the goods of being in the game industry = Going to work everyday with people you like, working on something that you love.

The con of being in the game industry = More money would be nice.

So that’s the lovey-dovey perspective on the industry, don’t get me wrong, it’s not all Kumbaya and s’mores but it passes the “Office Space” Test. If I had a butt-load of money and I didn’t need to work…God help me I’d still get up and drive through L.A. traffic to show up every morning.

This was going to be the part where I say that I wouldn’t actually show up every morning if I was suddenly rich, but I can’t. I’m scared to death to admit it, but I would show up every morning…it beats the hell out of daytime TV.

Posted in Gaming

1 Comment

Rails Observer Field

Written by Moe on September 11, 2008 | 3 Comments

The Rails observer field is an easy way to add an ajax select menu to your site. Below is an example to get you going.

Problem

Let’s say you have a list of users on your site and want to filter them by a group. In the example we will be using gym members.

View

<%= select "gym", :gym_id, Gym.find(:all).collect { |p| [p.name, p.id]}, {:selected => params[:gym]}  %>
<%= observe_field "gym_gym_id", :url => { :action => :members_by_gym , 
                                          :controller => :members},
                                          :update => "member_list", 
                                          :with => "'gym='+ escape($('gym_gym_id').value)" %>
<div id="member_list">
   <% for member in @members %>
      <%= link_to member.name, member %><br/>
    <% end %>
</div>

The first thing we do is build the select form by using the Rails Select Helper. The id of the select tag is generated by rails, “gym_gym_id”. We need to pass the id name as the first parameter to the observe field. The url parameter is pretty straightforward. The update parameter of the observer field designates which element will be updated. The “:with” parameter adds a parameter to the form named “gym”.

Post

Parameters: {"contoller"=>"members", "action"=>"members_by_gym", "gym"=>"1", "controller"=>"members"}

The “gym” parameter posted here is from the observer_field tag.

Controller

def members_by_gym
     @members = Member.find_all_by_gym_id(params[:gym])
     render :layout => false
  end

It’s important that you add the render :layout => false or bad things will happen. We still have one more thing to do. We have our controller being hit via ajax when the select menu changes but we need to make the html that will be updated on the page. In the view/members folder we need to make a new page called members_by_gym.html.erb

members_by_gym.html.erb

<% for member in @members %>
     <%= link_to member.name, member %><br/>
<% end %>

This code will be interpreted and update the “member_list” element on the page. That’s it. Rails Ajax magic.

Posted in Rails, Ruby, Technology

3 Comments

Game Corner?

Written by Aaron on September 8, 2008 | 4 Comments

Moe asked me if I’d like to post here on the BadPopcorn blog, to talk about random game industry stuff. Maybe I should have said no.

Well it’s too late now, I said “I’d love to” or something similar and now I will have to live with the repercussions of my reckless words. I’m starting small though.

There is this odd thing that can happen when participating in team activities, where one person on the team is more burden than benefit, like an obsolete laptop computer, they’re heavy, slow, loud and only rarely useful (and even then only for short periods of time). When we play Halo3 at the BadPopcorn office that laptop is me.

So really, what can the guy with the most deaths and least kills say to the rest of the team? “Uh Sorry I suck guys”? Even if it is sincere, it isn’t going to make the sucking stop, the sucking will continue. I do not have an “A-Game” that I have been not bringing, that can be brought now that I have realized my suck-ocity. To paraphrase Descartes, I suck therefore I am.

So what can the guy that drags the team down do?
Well I could stop playing, but screw that, the game is fun even when I come in last…unerringly, completely, utterly last. As discussed earlier an apology just doesn’t seem right unless I intend to do something to lessen the chances of similar wronging in the future. I’m afraid I cannot promise that.

Leaving only one option, a simple and heartfelt admission of wrongdoing and regret…

So yeah, Moe. That rocket in your back when you were trying to splatter Ben on the Mongoose?

My Bad

Posted in Gaming, Satire

4 Comments

Google Charts in Rails, gchartrb

Written by Brian on | 3 Comments

This week I was playing around with Google Charts, a wonderful API for creating charts via a URL. While I developed a helper class to create charts more easily in Rails, I did a little research and realized the RubyGem gchartrb has a great API for creating these charts. Here’s a quick tutorial on using gchartrb from the ground up.

Installing gchartrb
To install gchartrb, simply use the command gem install gchartrb from your command prompt. Check out these instructions for additional help and to access the gchartrb packages (Downloadable here).

Quick Examples
Now that we have our gem installed, we can create graphs right away. First, remember to require the gem at the top of your code. Notice how the gchartrb gem is actually called “google_chart”:

1 require 'rubygems'
2 require 'google_chart'

There are a couple ways that you can create a chart. You can instantiate the graph and then add attributes to it:

1 lc = GoogleChart::LineChart.new("400x200", "My Results", false)

Alternatively, you can create the graph and add the attributes within a block:

1 GoogleChart::LineChart.new("400x200", "My Results", false) do |lc|
2 # Put lc data here
3 # ...
4 puts lc.to_url
5 end

I personally prefer the latter method, as the creation of the graph and its attributes are kept together in a modular fashion.

Here are some examples of line, bar, and pie charts:

Line Chart

1 lc = GoogleChart::LineChart.new("400x200", "My Results", false)
2 lc.data "Line green", [3,5,1,9,0,2], '00ff00'
3 lc.data "Line red", [2,4,0,6,9,3], 'ff0000'
4 lc.axis :y, :range =&gt; [0,10], :font_size =&gt; 10, :alignment =&gt; :center
5 lc.show_legend = false
6 lc.shape_marker :circle, :color =&gt; '0000ff', :data_set_index =&gt; 0, :data_point_index =&gt; -1, :pixel_size =&gt; 10
7 puts lc.to_url

Notice that each lc.data call will create a new data line for you. The second parameter accepts a integer or float array, which can be anything you like. Lets say you have a WeighIn model that has weight as an attribute and belongs to some Person. If a person weighs himself/herself once a month for a year, then we can collect that data and show your trend via a line graph. Collecting that data and using it would look like this:

# In the controller Person
def show
@person = Person.find(params[:id])
weigh_ins = @person.weigh_ins.collect(&amp;:weight)

lc = GoogleChart::LineChart.new("#{width}x200", "My Results", false)
lc.data "Weigh ins", weigh_ins, green
# etc, etc...
puts lc.to_url # Or @line_graph = lc.to_url
end

Another useful function, lc.axis, can be used to specify your own data range labels, but it is not required to create a chart (default ranges and labels will be used). The last function, lc.to_url, takes the information specified for the line chart and puts it into the Google charts url.

Bar Chart

1 bar_1_data = [350,110,700]
2 bar_2_data = [200,800,50]
3 color_1 = 'c53711'
4 color_2 = '0000ff'
5 names_array = ["Bob","Stella","Foo"]
6 GoogleChart::BarChart.new("600x300", "Horizontal Bar Graph", :horizontal, false) do |bc|
7 bc.data "FirstResultBar", bar_1_data, color_1
8 bc.data "SecondResultBar", bar_2_data, color_2
9 bc.axis :y, :labels =&gt; names_array, :font_size =&gt; 10
10 bc.axis :x, :range =&gt; [0,1000]
11 bc.show_legend = false
12 bc.stacked = true
13 bc.data_encoding = :extended
14 bc.shape_marker :circle, :color =&gt; '00ff00', :data_set_index =&gt; 0, :data_point_index =&gt; -1, :pixel_size =&gt; 10
15 puts bc.to_url
16 end

An interesting attribute to pay attention to is bc.stacked, which gives you the ability to stack bar data, or to create separate bars together. When bc.stacked = false, the chart above is what is shown.

If bc.stacked = true, the same data will look like this:

Also, if you wanted to use this code in one of your controllers, and then display the graph in a template (view) file, you would set the graph’s url in the controller: @graph = bc.to_url Then within the view, you can simple show the graph as an image like this:

<!-- From within the view file --> 
<img src="<%= @graph %>"/>

Pie Chart

1 GoogleChart::PieChart.new('320x200', "Pie Chart",false) do |pc| 
2 pc.data "Apples", 40 
3 pc.data "Banana", 20 
4 pc.data "Peach", 30 
5 pc.data "Orange", 60 
6 puts "\nPie Chart" 
7 puts pc.to_url 
8 # Pie Chart with no labels 
9 pc.show_labels = false 
10 puts "\nPie Chart (with no labels)" 
11 puts pc.to_url 
12 end

This last example was taken from gchartrb’s readme file, which has an example for each kind of chart you can create (including Venn diagrams, Scatter charts, XY Line charts, etc). Notice that the data does not need to be within 0 to 100 (like percents on the pie chart) - the data will be added together and scaled appropriately by gchartrb. If you want to make the chart 3d, either set the 3rd parameter on PieChart.new to true, or you can set the attribute manually: pc.is_3d = true

Useful parameters

Google charts, by default, works with the data range between 0 and 100. Most of the time, your values will not work with this same scale. Instead of converting your data to the default scale, you can specify the data range with the :range parameter in bc.axis. So if you data was between 1 and 12 on the x_axis (like months in a year), then you could specify that range like so:
lc.axis :x, :range =&gt; [1,12], :labels =&gt; month_names_array

If you’re working with large data sets/numbers, then you may have chart data that is slightly off the mark. The default encoding that gchartrb uses is called Simple Encoding, which only has 62 points of resolution. We can easily expand this resolution (to 4096 points of resolution) by using Extended encoding, which a chart can select by changing the data_encoding attribute with :extended. For a line graph lc, it would look like this: lc.data_encoding = :extended. See Chart data for an explanation for all the encodings Google charts uses.

gchartrb subtlities

While gchartrb provides a great API for create charts in Rails, there are some subtle details about gcharts that you should be aware of. First of all, all charts derive from the base class GoogleChart::Base - check it out to see all the methods and attributes that apply to all charts. Secondly, gchartrb encodes all of the data values in some_chart.data from numeric form into a string representation of the data. This conversion doesn’t effect the final output of your chart, and helps make the chart url shorter in length. Again, if your working with large values, make sure the use the extended coding by using lc.data_encoding :extended.

Other Resources
Now that you have a taste of Google Charts with gchartrb, check out the API documentation here. If gchartrb doesn’t suit your tastes, you can go directly to the Google Charts API - it is thorough and self-explanatory. Ajaxian shows a number of quick examples of Google Charts here, and Matthew Bass gives a solid introduction to Google Charts and a few examples with gchartrb here. Lastly, here is a great link for 50 Cool Things You Can Do with Google Charts.

Posted in Google, Rails, Ruby, Technology

3 Comments