Posts tagged as:

tutorial

You can get cassandra at cassandra.apache.org and the ruby gem by running:

gem install cassandra

I did run into a problem with the trift_client gem when installing. If you get a Load Error, run this.

sudo chmod 644 /usr/local/lib/ruby/gems/1.8/gems/thrift_client-0.6.3/lib/thrift_client/*.rb
sudo chmod 755 /usr/local/lib/ruby/gems/1.8/gems/thrift_client-0.6.3/lib/thrift_client/connection

Here are some of the Cassandra commands from the video:

#connects to the cassandra server using the Twitter keyspace
store = Cassandra.new(“Twitter”)

# create a new column family in the Twitter keyspace called Users
cf_def = CassandraThrift::CfDef.new(:keyspace => “Twitter”, :name => “Users”)
store.add_column_family(cf_def)

# add or create a row to the column family
store.insert(“Users”, “cmaxw”, {“name” => “Charles Max Wood”, “description” => “Awesome coder”})

# remove a column from a row
store.remove(“Users”, “cmaxw”, “description”)

Download 17.2 MB
Download (iPod & iPhone) 20.9 MB
Take the 2011 Readers Survey

{ 5 comments }

Specification

  • Clicking a star rating turns on the stars to the left of the star I clicked.
  • Clicking a star submits the star rating.
  • When I refresh the page, the star ratings should be persistent.

We’ll be using Rails’ functions including:

  • form_for
  • hidden_field
  • Rails Helpers

We’ll be using jQuery functions including:

  • click
  • each
  • ajax

<code>
<% form_id = “movie_#{movie.id}_rating” %>
<%= form_for movie.ratings.last || movie.ratings.build, :html => {:id => form_id , :class => “star_rating_form”} do |f| %>
<%= f.hidden_field :movie_id %>
<%= f.hidden_field :stars, :id => form_id + “_stars” %>
<% end %>
<% (1..5).each do |i| %>
<li id=”<%= form_id %>_<%= i %>” data-stars=”<%= i %>” data-form-id=”<%= form_id %>”></li>
<% end %>
</code>

<code>
var set_stars = function(form_id, stars) {
for(i=1; i <= 5; i++){
if(i <= stars){
$(‘#’ + form_id + ‘_’ + i).addClass(“on”);
} else {
$(‘#’ + form_id + ‘_’ + i).removeClass(“on”);
}
}
}

$(function() {
$(‘.rating_star’).click(function() {
var star = $(this);
var form_id = star.attr(“data-form-id”);
var stars = star.attr(“data-stars”);

$(‘#’ + form_id + ‘_stars’).val(stars);

$.ajax({
type: “post”,
url: $(‘#’ + form_id).attr(‘action’),
data: $(‘#’ + form_id).serialize()
})
});

$(‘.star_rating_form’).each(function() {
var form_id = $(this).attr(‘id’);
set_stars(form_id, $(‘#’ + form_id + ‘_stars’).val());
});
});
</code>

{ 4 comments }

CoffeeScript is now going to be a default installation with Ruby on Rails. So, I installed CoffeeScript and NodeJS and have been playing with it for the last hour or so.

Here are the basics you need to know to use CoffeeScript including functions, arrays, hashes (objects), control functions (if, else, unless) and loops.

In my opinion it is friendlier than JavaScript and more terse, but I don’t feel like it’s a huge win over JavaScript. That being said, it is something I’m likely to use in the future.

Download 168 MB
Download (iPhone & iPod) 87.3 MB

{ 81 comments }

This video goes over some issues that popped up while upgrading a Rails 3 application to the Release Candidate

This video goes over some issues that popped up while upgrading a Rails 3 application to the Release Candidate.
Download 131 MB
Download (iphone & ipod) 11.7 MB

{ 6 comments }


Every good project needs a good setup. In this episode, I set up a github repo, create a new rails application, hook in Cucumber and Rspec, write a Cucumber feature, and write the code to make it pass.
Download 142 MB
Download (iphone & ipod) 59 MB

{ 27 comments }

Serving static pages with Rails Metal is actually very simple. Here are the assumptions we’re making.

  • Each static page’s content is made up of valid HTML.
  • Each static page has a path and content stored in a StaticPage object as defined by the StaticPage model.
  • If the path browsed matches the path in a StaticPage object, the content is what is to be delivered.

Here’s the code: [click to continue…]

{ 2 comments }

A few weeks ago, I wrote 9 Ways to Use Rails Metal. The third way to use Rails Metal was implementing a simple API.

Before I provide the code and an explanation, I’d like to cover a few things. First, this API only requires an API key. If you want an authentication token or some other identifier, look at Rails Metal Example #1: Authentication for some ideas of how to manage authentication for your API. Second, I didn’t filter any contents on the User model, so the password is passed back by the API. A simple delete call for the keys you want to omit from the hash returned by the find_by_sql call should clear up any data you don’t want to pass back.

Here’s the code:

# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

class ApiHandler
  def self.call(env)
    req = Rack::Request.new(env)
    @params = req.params
    if (env["PATH_INFO"] =~ (/^/api/(xml|json)/user//)) && ApiKey.find_by_key(@params["key"]) && env["REQUEST_METHOD"] == "POST"
      format = env["PATH_INFO"].split("/")[2]
      return [200, {"Content-Type" => "application/xml"}, [User.find_by_sql(["SELECT * FROM users WHERE id = ?", @params["id"]]).to_xml]] if format == "xml"
      [200, {"Content-Type" => "application/json"}, [User.find_by_sql(["SELECT * FROM users WHERE id = ?", @params["id"]]).to_json]] if format == "json"
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end

The code here is pretty simple. You check the path to make sure it matches the api path for XML or JSON, then find the record, convert it, and send it off to the user.

A few things to note are that the Rails methods to_json and to_xml are available in Rails Metal. I also had to explicitly return on the xml format because it isn’t the last execution and therefore isn’t returned.

{ 1 comment }

A week and a half ago, I posted 9 Ways to Use Rails Metal. The fourth way I listed was “Redirecting Affiliate Links.” The basic idea is that you can set up http://mydomain.com/hosting to go to the link you were given by the hosting company you have an affiliate account with.

The first thing I did was set up a model to manage affiliate redirects.

script/generate model affiliate_redirect path:string location:string

Then I ran my migrations, to set up the database.

rake db:migrate

Then I set up a Rails Metal instance called affiliate_redirects.

script/generate metal affiliate_redirects

From there, programming Rails Metal was pretty simple. You just have to find an AffiliateRedirect with the path visited and redirect to the AffiliateRedirect’s location. Here’s the code:

require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

class AffiliateRedirects
  def self.call(env)
    redirect = AffiliateRedirect.connection.select_all("SELECT * FROM affiliate_redirects WHERE path = '#{env["PATH_INFO"]}'").first
    if redirect && (location = redirect["location"])
      [302, {"Content-Type" => "text/html", "Location" => location}, ["You are being redirected."]]
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end

This is the quick solution to the Rails action with nothing but a redirect_to.

{ 0 comments }

Rails Developers do it with Models

I saw a t-shirt at Mountain West RubyConf this year that said “Rails Developers do it with Models.” Of course, they were talking about the classes we use to access the database. In fact, in Ruby on Rails, when you think of your data, you usually think of Models, not the database. The database is more a mechanism for remembering the data when you’re not using it.

Let’s look at one of the files that were generated in Part I. This file is where the model for our blog’s posts are defined.
[click to continue…]

{ 0 comments }

When I started writing part II, I started writing about models. As I got a little further along, I realized that it would be more helpful to provide an overview of the controller, which provides the data that goes into your web page, before I showed you how to get the data out of the database. My hope is that you’ll read this thinking of how you want the data provided, which adds context to part III on models.

Controllers are Where the Work Gets Done

Have you ever worked with one of those people who knows exactly where to go to get everything he needs. Can delegate his tasks effortlessly, and then pull it all together in the end. That guy would be our controller. When your website’s user browses to the page, the Rails engine picks up the request and decides which controller to send it to. More specifically, it decides which method in the controller to send it to. The methods on the controller are referred to as actions.
[click to continue…]

{ 0 comments }