dnite’s ‘old’ Blog

For my new blog, head over to http://blog.dnite.org

  • Moved Out!

    Thanks for stopping by my blog! It's been fun over here at Wordpress.com but I've moved to bigger, better things. My new blog is located here! Hope to see you there!

Archive for the ‘Ruby on Rails’ Category

Moving out…

Posted by dnite on March 8, 2007

WordPress.com has been good to me for some time but it’s my time to move on out on my own. From now on, you’ll find me at http://blog.dnite.org (and probably just plain http://dnite.org as well). I’ll be doing most of my development and rails blogs over there as well as release the plugins I’ve released here over there. See you there!!

Posted in Blogs, Misc., Ruby on Rails, Web development | Leave a Comment »

OpenID testing in rails

Posted by dnite on March 2, 2007

UPDATE: I’ve moved my blog to http://blog.dnite.org and updated this into a real plugin. You can check it (and anything else I have going on) over there.

It’s all the rage lately. OpenID has quickly become huge as of late. With huge companies like digg, microsoft and aol picking up and supporting OpenID, it’s just a matter of time before we’re all basking in OpenID glory and wondering what we ever did without it.

For those of you not in the know, OpenID presents a decentralized universal login. Basically, your URL is your login name. When you visit a site that accepts OpenID logins, you give them your OpenID URL and your forwarded to your OpenID server to log in. Once you log in, your redirected back to where you came from pretty seamlessly. It’s really cool stuff with a lot of potential. It offers a nice speed bump for spammers on a lot of blogs. It also offers a way for people to keep track of the same person across multiple sites. If you have a friend you met on xyz.com, you can rest assured that it is the same person you happened across on abc.com as well.

Less than a week ago, DHH added a plugin to the official Rails subversion repository that wraps around some of the lose ends for accepting OpenID logins in your Rails application. It’s early in development but it works quite well. Pick it up and read through the README for basic instructions on how to get things working.

Recently, I started training myself to do Test Driven Development. I bought the GREAT peepcode screencast on the topic and got started. This means that I’m writing tests for everything and I essentially won’t really look at my site until it’s close to done. So after I implemented OpenID into my new application, I needed a way to write some tests for it. I didn’t want to hammer a OpenID server with constant testing so I wrote up a ‘stub’ that I figured I’d share with others wishing to write tests for their OpenID applications. It’s very basic right now. I’ll probably improve it shortly down the road, but for right now. It’ll do.

Posted in OpenID, Ruby on Rails, Web development | 2 Comments »

Self Referential Two Way Friends Ruby on Rails Plugin

Posted by dnite on January 26, 2007

UPDATE (3/08/2007) :: I’ve moved my blog and this plugin (an updated version at that) over to http://blog.dnite.org. If you want more information and would also like to download it, head over there. That’s where I’ll be residing from now on.

Posted in Ruby on Rails, Web development | 5 Comments »

Ruby on Rails :: Restful friends with has_many :through

Posted by dnite on November 25, 2006

EDIT (2007-03-07) :: I’ve updated this as a plugin and released it at my new blog (http://blog.dnite.org). I’ll keep this information up here, but everything is a lot cleaner and works a lot better with the new plugin. So go check out my new blog!

EDIT (2007-01-23) :: I’m depreciating this entry/tutorial!! If you have problems getting this working, just be patient, I’m going to be releasing a plugin in the very near future that will work a lot better and be a lot easier to impliment than this! Just give me a few days…I’ve been working on a project of mine and while I learn Rails. One thing that surprised me was that as many tutorials there are on how to create a blog, there are very few about creating a friends system. So I’ll try and go through the system I put together today after many headaches (that I’ll explain later).

We’re going to keep it RESTful here (or as RESTful as we can). I’ve found that the easiest way to approach anything RESTfully is to understand the path first. So let’s start there. These are the path’s we’ll need to accomplish our friends methods.

# List a user's friends (index action, GET method)
/users/1/friends

# Confirm that a user wants said friend. (confirm action, GET method)
/users/1/friends/2;confirm

# Add a friend (add action, POST method)
/users/1/friends/2;add

# Remove a friend (destroy action, DELETE method)
/users/1/friends/2

# Show a friend
/users/1/friends/2 (show action, GET method)

We’ll need a couple of models, a couple of controllers, and a couple of routes. I’m assuming you know how to make a new Rails project, so let’s get started by creating the models. We’ll need a User model and a Friendship model. I’ll keep them simple here.

First, here’s the tables I created.

create_table :users do |t|
t.column :name, :string
t.column :created_at, :datetime
end

create_table :friendships, :id => false do |t|
t.column :user_id, :integer, :null => false
t.column :friend_id, :integer, :null => false
t.column :status, :integer, :null => false, :default => 0
t.column :created_at, :datetime
end

The models look like this.

class User < ActiveRecord::Base
has_many :friendships
has_many :friends, :through => :friendships
end
class Friendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User', :foreign_key => 'friend_id'
end

Now, here’s where I was pulling my hair out. Because, in theory, that association looks ok to me. But if I try and do something like…

User.find(1).friends

I get a nice and very strange SQL error.

Mysql::Error: Column 'friend_id' cannot be null: INSERT INTO friendships (`status`, `user_id`, `created_at`, `friend_id`) VALUES(0, 2, '2006-11-25 01:06:46', NULL)

The strange part isn’t the error. It’s that, one, there is no friend_id (and I still have no idea why) and two, it’s putting what SHOULD be the friend_id into the user_id column in the table. I still have yet to figure out why this happened, so I just went ahead and made my own little work around which works just fine and in all technicality, will probably work better down the road when I have more attributes in the friendships model. But if anyone has any ideas on what could be wrong, I’d love to hear about it.

Anyways.. Back on topic. Now we have the relationships, we need to interact with them. Being RESTful says that we need to do something like /users/1/friends/2 with the correct method. So I created a friends controller that looks like this.

class FriendsController < ApplicationController
def confirm
@friend = User.find_by_id(params[:id])
@current_user = current_user
end
def add
if !friends_already?(params[:user_id], params[:id])
add_friend(params[:user_id], params[:id])
end
redirect_to users_path
end

def destroy
if friends_already?(params[:user_id], params[:id])
remove_friend(params[:user_id], params[:id])
end
redirect_to users_path
end

protected
def friends_already?(user_id, friend_id)
user = User.find(user_id)
friend = User.find(friend_id)
return true if user.friends.include?(friend) && friend.friends.include?(user)
false
end

def add_friend(user_id, friend_id)
Friendship.create({:user_id => user_id, :friend_id => friend_id})
Friendship.create({:user_id => friend_id, :friend_id => user_id})
end

def remove_friend(user_id, friend_id)
Friendship.delete_all "user_id = #{user_id} and friend_id = #{friend_id}"
Friendship.delete_all "user_id = #{friend_id} and friend_id = #{user_id}"
end
end

The confirm action (/users/1/friends/2;confirm) shows a dialog w/ a button that lets the user confirm that he wants to be friends with this person. The button posts to /users/1/friends/2;add. From here it’s pretty self explanitory. It looks really nice when you can call /users/1/friends to list all of someone’s friends. Any extra attributes needed can be added in the add_friend action. Now all you need to do is add the new cool restful routes to config/routes.rb

map.resources :users do |user|
user.resources :friends, :member => { :confirm => :get, :add => :post }
end

That should do ya. Sorry this isn’t a full out tutorial, but you should definately have a good idea on how to impliment a friends system pretty quickly now. Make changes. Do what you want. Let me know if I screwed anything up. I’m still learning this stuff, so what I have here could be completely stupid. Let me know what you think.

Posted in Ruby on Rails, Web development | 9 Comments »

More Ruby on Rails with Ubuntu… (rails.vim)

Posted by dnite on November 10, 2006

UPDATE: I have updated this entry on my new blog at blog.dnite.org. That link is a direct link to the updated article.

I wrote an article not too long ago about installing Ruby on Rails on Ubuntu (Edgy) quickly and easily. The one section I left pretty ‘in the air’ was definitely the IDE. I feel that Linux has the biggest choice when it comes to editor options.

If your using Windows, you’ll probably use RadRails. It’s feature rich. It does everything you need. And windows Java machine just seems to work more efficiently, in my experience, than the ones for linux. If anyone wants to give me some hints to improve my java machines performance, go right ahead. On the mac. You have TextMate. Mac’s also have a lot of options, but from what I’ve heard and seen. Very seldom do you develop Rails applications on a mac without using textmate.

Now, for Linux, you have a variety of things to choose from and I’ve dipped my hands in a few of them. First, I tried RadRails. RadRails is what I used in windows and it was familiar to me. Since it runs on all 3 platforms, I figured I’d give it a shot in Linux. The problem was, that it just seemed a lot slower than it ran in Windows. I’m not exactly sure why this is, but speed and reliability were the reasons I went looking for a better alternative. I did some research and found that some people used jEdit. But getting jEdit to work in Edgy was a chore, do I didn’t even try. gEdit was also another option. It highlights syntax. It can take plugins. It’s a pretty light weight editor. I tried this for a couple of days, but it just didn’t feel right.

Over in the #rubyonrails IRC channel on irc.freenode.net, I heard about vim and a plugin called rails.vim. I’d given vi a try a long time ago. But never a substantial try. It was always really confusing to get into right away. It’s just not like most other editors. But I figured I’d give it a shot anyways. After a week or so of working with Vim and rails.vim, I’m pretty sold. I’m not 100% comfortable with it just yet, but I can definitely see the potential. I find myself hitting ESC and starting to type :wq when quickly editing something in gEdit or something. Rails.vim takes vim a step further and adds a ton of nice Rails features. Here’s what I did to get into and start enjoying using vim in a couple of days.

First and foremost. Make sure you have Vim installed. Pretty simple. The vimtutor command is optional but VERY VERY recommended if you’ve never used vim. Take the half hour to complete the tutor and you will understand vim a lot better.


sudo apt-get install vim-common vim-runtime vim-gnome
vimtutor

Now that you have vim installed, let’s install the vim ruby gem that gives you all the nice syntax highlighting and other cool ruby features. When you run vim-ruby-install.rb, it gives you the option to install to your home folder. I picked this option, so make sure you don’t run this with sudo.


sudo gem install vim-ruby --remote
vim-ruby-install.rb
(select option 1 when it asks where you want to install. /home/username/.vim)

Now you should have Vim installed with some nice ruby stuff. Let’s go ahead and make a startup file to get rid of a few vim annoyances. Create a new file called .vimrc in your home directory (~/.vimrc) and add the following.


set nocompatible
syntax on
filetype plugin indent on
set mouse=a

runtime! macros/matchit.vim

augroup myfiletypes
autocmd!
autocmd FileType ruby,eruby,yaml set ai sw=2 sts=2 et
augroup END

Now, all we have to do is download rails.vim. Head over to rails.vim and download the latest version. There should be a plugin directory and a doc directory in this archive. Extract it to your .vim folder and your all set. The last thing you have to do is enable the rails documentation.


vim
:helptags ~/.vim/doc

With rails.vim installed, you can launch vim from your project directory and have a lot of new functions. If you try :Rmodel user (which tab completes very nicely), it opens up app/models/user.rb. :Rcontroller blog will open up app/controllers/blog_controller.rb. Everything works just like you would expect it to. You can tab complete the commands and the filenames. If you don’t know what file your looking for, leave the filename off and start hitting tab. You’ll just cycle through all the models or controllers or views. :Rextract will take a currently highlighted section of your code, and automatically create a new partial file while replacing the current selection with the render :partial call. Also, if you move the cursor over another controller name or model name or anything similar and press gf, you will open up that file. It takes a little getting used to but it really works. For a completely list of everything that rails.vim can do, type :help rails. There’s a lot you can do.

Hope that helped out some people! Enjoy!

Posted in Linux, Ruby on Rails, Ubuntu, Web development | 10 Comments »

Ruby on Rails on Ubuntu

Posted by dnite on October 24, 2006

This post has moved over to my new home. blog.dnite.org. Head over there for any updates or whatever.

It seems as though all the information for getting a full Ruby on Rails system up and running in Ubuntu is pretty scattered about the web, so I thought this makes a perfect opportunity to go ahead and condense it all in one place. From start to finish.. Here we go..

Install Ruby

First we need to install ruby and a few extra things so we don’t have issues later. just installing ruby will work to some degree, but things will break later.

sudo apt-get install ruby ruby1.8 ruby1.8-dev rdoc ri irb

Install MySQL

A lot of Rails folks like to use sqlite.. i haven’t tested it but I believe that’s as easy as ‘sudo apt-get install sqlite3’. Could involve more steps though. Here’s what I did to install MySQL.

sudo apt-get install mysql-server libmysql-ruby

Then, just to be safe, lets add a password for root.

mysqladmin -u root password NEW_PASSWORD
sudo /etc/init.d/mysql restart

You may want to go ahead and create your databases now, or save it for later…

mysql -u root -p

Install Ruby Gems

Ruby Gems will install a majority of Rails and any other cool stuff we need specific to Ruby. There’s no package of it availiable for ubuntu (as of right now) so you’ll have to download it yourself. The current version as of today is 0.9.0, but make sure that’s the most current version before following the steps below exactly by going to http://rubyforge.org/frs/?group_id=126. If it’s not, then just replace the url below with the url to the most current version.

wget http://rubyforge.org/frs/download.php/11289/rubygems-0.9.0.tgz
tar zxvf rubygems-0.9.0.tgz
cd rubygems-0.9.0
sudo ruby setup.rb

Install Rails

Next it’s time to install Rails. If you followed all the directions till now, it shouldn’t be a problem. I have run into the problem of rdoc spilling out a bunch of errors if you failed to install that. I’ve also read that you have to be in your home dir to perform this step. Not sure if that’s true, but it couldn’t hurt.

cd
sudo gem install rails --include-dependencies

Install an IDE (optional)

You should now have a fully operational Ruby on Rails install right now. The next step would be to choose how you want to work on your web applications. Linux has a whole slew of editors you can use. Vim is a popular choice among the rails novices. If your looking for something a little more user friendly and easy to get into, RadRails is very nice for this. There is no package for RadRails, but lucky enough, RadRails is enclosed in a single folder you can toss just about anywhere and run from there. I extracted it to /opt/radrails and created a small file to run it in /usr/bin… This is all completely up to you. However you feel most comfortable working.

EDIT: I actually did a new piece on using Vim as your ‘IDE’ for rails. Take a look.

Install RMagick (optional)

Another problem I ran into was getting ImageMagick and RMagick installed and working right in ubuntu. If you will be needing photo manipulation support for your web app, use these instructions for installing RMagick.

sudo apt-get install imagemagick
dpkg -l | grep magick

You will see a list of the imagemagick packages that were installed. There should be one that starts with lib and ends with a number. Mine was libmagick9, so below, if you have anything but libmagick9, replace the number below.

sudo apt-get install libmagick9-dev
sudo gem install rmagick

rmagick takes a little while to build. So go grab something to eat or drink.

Conclusion

Looking back, getting Ruby on Rails is not all that hard to do in ubuntu, but having information that was either old or scattered in many places made it a pain in the ass for me. So I hope someone comes across it helps them out a bit. I’m pretty sure I got all the instructions right, but if something happens to not work, leave a comment and I’ll try and help.

EDIT:
It would figure that the first day that wiki.rubyonrails.com is down in.. forever? is the day that I chose to try and install rails on ubuntu myself. Most of this information is up there, but I went ahead and added the last part about image magick there, So check out wiki.rubyonrails.com.. You can get just about anything there. x=)

Posted in Linux, Ruby on Rails, Ubuntu, Web development | 14 Comments »