Monday, March 30, 2009
Rails Video Application
Earlier this semester, I decided I wanted to keep working on my Video Application(see the Flash Video Tutorial). So when my databases teacher let us decide what our semester project would be, I signed up to do a YouTube-like site.
Since the tutorial, I've added a lot of things: User Authentication(authlogic), Video Thumbnails(using ffmpeg), Pagination(will_paginate), Tags/Tag Cloud(acts_as_taggable_on_steroids), and I wrote up some quick code to take care of user replies. I also added a little bit of CSS to the application so it didn't look so plain. It looks a lot better, but I'm still working on some of it. You can checkout the code for it on GitHub(http://github.com/balgarath/video-app/tree/master). The code from the previous tutorial is in the 'Tutorial' branch.
Anyway, I will have a demo of the application up sometime the next couple days. I'll get the URL posted here. Feel free to fork the repo and play around with the app.
Wednesday, March 18, 2009
Yehuda Katz talks about Rails 3.0
Just got through watching Yehuda Katz's talk about Rails 3.0 he gave at MountainWest RubyConf 2009. Lots of good stuff about where Rails is headed, as well as the ORM-abstraction that Yehuda is working on, ActionORM. ActionORM is a layer built to make any ORM look just like it is ActiveRecord, to Rails. Yehuda also talks a little bit about how he is working to change rails so that it will be easier to do things such as changing out ORMs, or even something like replacing ActionController with your own Controller code.
Towards the end he talks about how some people have said that by Merb merging with Rails, there will be less competition, and there will be less competition. Yehuda points out that by making rails modular, competition will be more between different parts of the framework(ActiveRecord vs. Datamapper). I agree with him and think that this will be a huge benefit to the community as a whole. Heres the video:
This video brought to you by ConFreaks. Lots of great videos at the website from many other Ruby-related conferences.
Thursday, January 22, 2009
Flash Video Tutorial with Rails, ffmpeg, FlowPlayer, and attachment_fu
Quick Tutorial today to get a simple Video Model setup and going with Flowplayer today. We want to be able to upload videos and convert them to flash .flv files. For this I'll be using ffmpeg. Other plugins in this tutorial include acts_as_state_machine and Rick Olsen's attachment_fu. Lets get started!
Note: You can find the source code for this app on github at http://github.com/balgarath/video-app/tree/master. EDIT: I've been working on this, so if you want to see the code specific to the tutorial, click on the Tutorial branch on github.
1. Setup
First, lets create an empty app
rails videoapp -d mysql
Do all your basic setup...(edit database.yml, remove public/index, ...). In routes.rb, add this line:
map.root :controller => "videos"
map.resources :videos
The first line maps '/' to the videos controller, and the next establishes RESTful routes for videos.
Now we need to figure out what flash video player we want to use. For this tutorial, I will be using FlowPlayer, an open-source flash video player. You will need to download flowplayer.zip from http://flowplayer.org/download/index.html. Unzip it to /public. Grab the /example/flowplayer-3.0.2.min.js file and put it in /public/javascripts/flowplayer.js. Put example/style.css in /public/stylesheets.
Next we need to install attachment_fu to handle file downloads.
./script/plugin install http://svn.techno-weenie.net/projects/plugins/attachment_fu/
And you will need ffmpeg for converting uploaded file to .swf. This works for me in Ubuntu...
sudo apt-get install ffmpeg
And last, lets install the acts_as_state_machine plugin. We will be using it to keep track of the current state of conversion for the video:
./script/plugin install http://elitists.textdriven.com/svn/plugins/acts_as_state_machine/trunk/
2. Database/Model Setup
Now we are ready to set up the model. First, run this command to generate the files for you:
./script/generate model Video
This last line will also generate a create_video migration in db/migrate/. Open up that file and put this in it:
class CreateVideos < ActiveRecord::Migration
def self.up
create_table :videos do |t|
t.string :content_type
t.integer :size
t.string :filename
t.string :title
t.string :description
t.string :state
t.timestamps
end
end
def self.down
drop_table :videos
end
end
Content_type, size, and filename are used by the attachment_fu plugin. The state field will be used by the act_as_state_machine plugin to keep track of video converting.
Lets move on to the model; open up /app/model/video.rb and add this into it:
has_attachment :content_type => :video,
:storage => :file_system,
:max_size => 300.megabytes
#turn off attachment_fu's auto file renaming
#when you change the value of the filename field
def rename_file
true
end
This is for the attachment_fu plugin. I came across a feature of attachment_fu: when you change the filename of an attachment, the old file automatically gets moved to whatever the new filename is. Since I am creating a new file and changing the filename attribute of the video the reflect that, I don't need this on...so I just overrode the method in the Model.
Since we will be using the acts_as_state_machine plugin to keep track of the state of conversion for videos, lets go ahead and add in the states we will be using. Add this to video.rb:
#acts as state machine plugin
acts_as_state_machine :initial => :pending
state :pending
state :converting
state :converted, :enter => :set_new_filename
state :error
event :convert do
transitions :from => :pending, :to => :converting
end
event :converted do
transitions :from => :converting, :to => :converted
end
event :failure do
transitions :from => :converting, :to => :error
end
Note: I got some of this part from Jim Neath's tutorial.
Now we can use @video.convert!, @video.converted!, @video.failed! to change the state of a particular Video. The last code we need to add to the model is this:
# This method is called from the controller and takes care of the converting
def convert
self.convert!
success = system(convert_command)
if success && $?.exitstatus == 0
self.converted!
else
self.failure!
end
end
protected
def convert_command
#construct new file extension
flv = "." + id.to_s + ".flv"
#build the command to execute ffmpeg
command = <<-end_command
ffmpeg -i #{ RAILS_ROOT + '/public' + public_filename } -ar 22050 -ab 32 -s 480x360 -vcodec flv -r 25 -qscale 8 -f flv -y #{ RAILS_ROOT + '/public' + public_filename + flv }
end_command
logger.debug "Converting video...command: " + command
command
end
# This updates the stored filename with the new flash video file
def set_new_filename
update_attribute(:filename, "#{filename}.#{id}.flv")
update_attribute(:content_type, "application/x-flash-video")
end
A lot of stuff going on here. Convert will be called from the create action. When called, it sets the state of the video to 'convert' and runs ffmpeg to convert the file to flash(.flv). It will then mark the file as either 'converted' or 'failed'.
Now that that is all done, we can create our database and run the migrations:
rake db:create
rake db:migrate
3. Controller/Views
Now we can generate our controller, model, and view files:
./script/generate controller videos index show new
Open up /app/controllers/videos_contoller.rb and put in this code:
class VideosController < ApplicationController
def index
@videos = Video.find :all
end
def new
@video = Video.new
end
def create
@video = Video.new(params[:video])
if @video.save
@video.convert
flash[:notice] = 'Video has been uploaded'
redirect_to :action => 'index'
else
render :action => 'new'
end
end
def show
@video = Video.find(params[:id])
end
def delete
@video = Video.find(params[:id])
@video.destroy
redirect_to :action => 'index'
end
end
In the create method, notice that if the video save is true, @video.convert gets called, which convert the video to .flv.
Views
Create the file /app/views/layouts/application.html.erb and put this in it:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Video Tutorial</title>
<%= stylesheet_link_tag 'style' %>
<%= javascript_include_tag 'flowplayer' %>
</head>
<body>
<h1>Video Tutorial</h1>
<% flash.each do |key,value| %>
<div id="flash" class="flash_<%= key %>" >
<span class="message"><%= value %></span>
</div>
<% end -%>
<%= yield :layout %>
</body>
</html>
Now for our index view (/app/views/videos/index.html.erb)
<h2>Videos</h2><br />
<%= link_to 'New Video', new_video_url %><br />
<% for video in @videos do %>
<p><%= link_to video.title, video %></p>
<% end %>
/app/views/videos/new.html.erb:
<h2>New Video</h2><br />
<% form_for(@video, :html => { :multipart => true }) do |f| %>
<%= f.error_messages %>
<table>
<tr>
<td><%= f.label :title %>: </td><td><%= f.text_field :title %></td>
</tr>
<tr>
<td><%= f.label :description %>: </td><td><%= f.text_area :description %></td>
</tr>
<tr>
<td><%= f.label :video %>: </td><td><%= f.file_field :uploaded_data %></td>
</tr>
<tr><td><%= f.submit 'Submit' %> - <%= link_to 'Back', videos_path %></td></tr>
</table>
<% end %>
This is the upload form. Notice I used f.file_field :uploaded_data...this is for attachment_fu to work. Next is /app/views/videos/show.html.erb:
<h1><%= @video.title %></h1>
<p><%= @video.description %></p>
<a
href="<%= @video.public_filename %>"
style="display:block;width:400px;height:300px"
id="player">
</a>
<!-- this will install flowplayer inside previous A- tag. -->
<script>
flowplayer("player", "/flowplayer/flowplayer-3.0.3.swf");
</script>
And that should do it. ./script/server and try uploading a movie file and see if it works. Also, you could probably mess around some with the call to ffmpeg and increase video quality. There are some good posts if you search for 'ffmpeg' over at the FlowPlayer Forums, and if you purchase a commercial license for the player, you can remove the advertising and get some new features, as well as support. Thanks for reading!
Update:
For a quick way to put the video conversion on a background process, I was able to use Tom Anderson's Spawn plugin. Note that this wouldn't be a very efficient way to scale it if you expect to have a lot of users uploading at the same time, as it forks another process to handle the conversion. This does work well if there aren't a bunch of videos getting uploaded at the same time. If you do need to scale the uploading, I recommend using Ap4r(Asynchronous Processing for Ruby). Here we go!
First, lets install the Spawn plugin from github:
./script/plugin install git://github.com/tra/spawn.git
And next, change the convert method in Video.rb to this:
# This method is called from the controller and takes care of the converting
def convert
self.convert!
#spawn a new thread to handle conversion
spawn do
success = system(convert_command)
logger.debug 'Converting File: ' + success.to_s
if success && $?.exitstatus == 0
self.converted!
else
self.failure!
end
end #spawn
end
And thats it! Now when you upload a video, you don't have to wait for the server to convert the video file over to flash.
Obama to Save Money by Investing in Open Source?
I believe it would be a great idea for the government to invest money in Open Source, and would be glad to see some of my tax money being invested in it..as long as the Ruby Community gets its chunk ;).
Friday, August 15, 2008
Juggernaut Push Server
Juggernaut is a Rails plugin that allows you to push information out to the client, without them having to specifically request it. For certain domains, a push server is an excellent solution. Juggernaut uses a small bit of Flash to open up a flashxmlsocket from the browser to the push server, and it subscribes to the service. My roommate Taelor has been playing around with it for a little while, and has put together a chat application that creates rooms off of Digg topics. Its called Shovel Chat. He has also made a few blog posts about Juggernaut and using it to create a chatroom with rails at his blog, and has posted the source code on GitHub(note that you will need to go through his blog posts and edit some of the gem's files...)
So, the way the chat app works is that when you request the show action for a chatroom, some flash gets sent to subscribe to the channel on Juggernaut. Juggernaut will then send you a list of all the people in the room. If you type in a message and hit enter, the message gets posted to your Rails app. Inside the controller, the message gets sent to the Juggernaut server, which then pushes the message out to anyone subscribe to that channel. You could achieve a similar effect using AJAX, but you would have to have each client polling the server for updates to the chatroom, but this would be really difficult to scale.
Anyway, I've gotten his source code installed on my machine and have begun playing around with it, and hope to start contributing to his chat_sandbox on github soon. Feel free to make your own fork of his code on github and start contributing, and stay tuned for more updates!
-Ralph
Tuesday, August 12, 2008
The Ruby Hoedown
Last Thursday, my roommate and I packed and headed 3 hours south to the Ruby Hoedown in Huntsville, AL. It was held at the Shelby Center at UAH on Friday and Saturday. This was my first programming conference, so I thought I might jot down a little bit about how it went.
The first presentation was by the guys at Rails Envy. They talked about innovation in Ruby over the past year. I'm a big fan of these guys' podcasts and tutorials, and they gave a great presentation.
Next up was Robert Dempsey, who talked about Cloud Computing with Rails. He made a great argument against all the folks who say that Rails can't scale. He gave us very detailed explanations of what a Cloud is, and what scalability is. He showed us what it takes to use Amazon Web Services to scale a site up, and then gave us a brief descriptions of different utilities out there for scaling with a cloud: Amazon Web Services, Heroku, Joyent, Accelerator, Morph. One particularly intresting platform was Vertebra, which is being developed by the folks at Engineyard.
Vertebra is a "Next Generation Cloud Computing/Automation Framework". Ezra Zygmuntowicz has some slides posted at his blog. The backbone of the system runs on horizontally scalable erlang XMPP servers. XMPP is an IM/chat protocol this is very efficient. Ezra posted this tidbit on his blog: "Just to answer the question about Vertebra being open source or not. Yes vertebra will be open source, the ruby framework, the protocols and security stuff will all be open source. We may go with a commercial license on the workflow engine as that is a large piece of engineering but we have not decided yet. We want to get this out there and see what people do with it as I think there are limitless possibilities here. But we need to lock down the protocol and document everything and we are still experimenting with different parts of the system. I'd hope to have something to release in 4-6 weeks." Yehuda Katz gave a talk about Vertebra on saturday, and I had a chance to chat with him for a few minutes. He mentioned that some of the folks from Heroku were helping out on the project.
Jim Weirich and Joe O'Brien gave a great talk about mocking. This was an interesting talk because they acted it all out like they were 2 developers working on different problems that involved using mocks. The first one involved using a mock object to log in during testing, and in another one, they showed how you can refactor code so that you will be able to use a mock with it. I chatted with these guys at lunch on Saturday for a while.
Rein Henrich gave a very entertaining talk on Ruby Best Practice Patterns. He started off with a comical presentation on code unfactoring. He showed us different methods of making your code so unreadable that you are the only person able to reasonably maintain it. "Job security through code obscurity." Some of the methods he showed us were: un-DRYing your code; naming methods and variables in pig latin; and taking code that is abstracted into several small functions, and dumping it all into one huge one. After the talk on code unfactoring, he went on into his real presentation on best practice patterns. One of my favorites was the execute around method.
Some other notable talks at the conference included: bryanl(blog smartic.us), who talked about why you should "Test all the fucking time"; the truthy gem; Obie Fernandez's great talk on running a successful company; keynote talks by Chris Wanstrath and David Black; Troy Davis did a presentation on Adhearsion, a ruby framework for making and recieving phone calls; Giles Bowkett used Ruby and his program Archaeopteryx, to create music with code; Being a guitar player, Giles presentation was very interesting to me..unfortunately, Archaeopteryx is only availible for the Mac right now.
I had a great time at the conference. It was cool to be around so many other Ruby enthusiasts, and everybody was really nice. I definitely plan on going next year. Jeremy mentioned that he is planning on holding the Hoedown at Opryland Hotel in Nashville(only an hour away!), and that he hopes to get enough sponsors to host it for free. Even if it isn't free next year, I will gladly pay out another $200 to go again. If you've never been to a conference before, I highly recommend it. It was a very gratifying experience.
Well, thats all for now, I know I promised a post about my Google Summer of Code project, but I don't have it all together yet. If you are interested, it is a c-extension to speed up some of Ruby's CGI functions. You can check out the repo on github here. Farewell until next time!
Edit: Also, you can get videos of all the talks at ConFreaks. I spent a while chatting with both of the guys there, and one of them let me plug in my laptop to their powerstrip for the majority of the conference(I need a new battery...).
Sunday, July 27, 2008
Been a little while...
Hi all, thought I would make a post and update things. I've been busy working on a couple of different gigs: My Place Media, and the Google Summer of Code. Anyway, My Place Media just ran out of money(lots of bad decisions by the guy calling the shots), so I've got a lot more time to concentrate on my GSoC project.
My GSoC project is to working on extending parts of Ruby's CGI class in C (mainly the query string parsing and multipart form parsing). My mentor for the project is Pratik Naik, a Rails Core member. I'll have some more info on how the project is coming along in another post.
Anyway, I've got some ideas for expanding RailsonEdge out a little. The first is that I've purchsed the domain name railsonedge.com, and I have a shared host server. What I would like to do is to use my server to provide hosting for a few open source Rails apps, and let the developers of them either post to the blog, or just put in a feed from their blog. So if there is anyone out there that would like free hosting for your Rails project, to show it to the world, shoot me an email at rledge21 -at- gmail -dot- com, and tell me a little about yourself and your project.
I'm planning on posting some new tutorials very soon (maybe even doing a screencast, but I've not decided whether my voice would scare everybody off or not), and putting up a code snippet repository (similar to snippets.dzone.com)
Anyway, that is what is going on. Expect some posts over the next couple weeks with a couple tutorials, as well as an update to my GSoC project...later all.
Friday, May 2, 2008
Using Symbols
If you all are anything like me, symbols confuse the hell out of you. You may use them, but you don't really understand them. I decided to research it out a little today and see what I could figure out. It turns out that there are a lot of different viewpoints of symbols out there. Here are some articles I came across:
The first is a detailed overview of symbols, the second shows some of the way Rails uses symbols.
So, as a quick summary, here is what I know about symbols:
A symbol is used to represent strings, without the overhead of actually creating a string. They don't have the functionality that you get with a string, and the value of them can't be changed, but they are much more efficient than using a string. Here is part of the example from the Gluttonous article:
> patient1 = { "ruby" => "red" }
> patient2 = { "ruby" => "programming" }
> patient1.each_key {|key| puts key.object_id.to_s}
211006
> patient2.each_key {|key| puts key.object_id.to_s}
203536
The key in both hashes creates(string "ruby") has a string object created each time. So, in this example, we have 2 seperate string objects with the same name. You can achieve the same result with symbols:
> patient1 = { :ruby => "red" }
> patient2 = { :ruby => "programming" }
> patient1.each_key {|key| puts key.object_id.to_s}
3918094
> patient2.each_key {|key| puts key.object_id.to_s}
3918094
The difference here is that the same symbol is referenced in both of these. Not only is symbol a smaller object, but it gets reused.
So I am curious, what ways do you all use symbols?
-Ralph
Thursday, May 1, 2008
Intro to the Rails Console
Hi all. Today I'm going to give you a bit of an introduction to the Rails console. Using it will make your life a lot easier. To open it up, type ./script/console from your project directory. From here you can play around, test out commands, add objects to the database if you haven't created an page to do it yet. I'll be using the console from my Forum tutorial to give you examples, so here we go!
First, let's load all of our topics from the database into a variable:
>> @topics = Topic.find(:all)
Which outputs the following:
=> [#<Topic id: 1, forum_id: 1, user_id: nil,
subject: "My Rails 2.0 Forum Tutorial",
body: "Check it out, http://railsonedge.blogspot.com",
created_at: "2008-03-06 11:11:07",
updated_at: "2008-03-06 11:11:07">,
#<Topic id: 2,
.......
Easy stuff. Now lets take that hash, and make it into something useful:
y @topics
The 'y' function outputs everything in yaml format, much more readable:
---
- !ruby/object:Topic
attributes:
updated_at: 2008-03-06 11:11:07
body: Check it out, http://railsonedge.blogspot.com
subject: My Rails 2.0 Forum Tutorial
id: "1"
forum_id: "1"
user_id:
created_at: 2008-03-06 11:11:07
attributes_cache: {}
- !ruby/object:Topic
attributes:
updated_at: 2008-03-06 11:11:37
body: Check it out! http://railsonedge.blogspot.com
subject: New Blog Post Today!!
id: "2"
forum_id: "1"
user_id:
created_at: 2008-03-06 11:11:37
attributes_cache: {}
- !ruby/object:Topic
attributes:
updated_at: 2008-03-09 00:35:44
body: Welcome to the new forum.
subject: Welcome!
id: "3"
forum_id: "2"
user_id:
created_at: 2008-03-09 00:35:44
attributes_cache: {}
- !ruby/object:Topic
attributes:
updated_at: 2008-03-09 00:36:04
body: What time is it?
subject: "Question:"
id: "4"
forum_id: "2"
user_id:
created_at: 2008-03-09 00:36:04
attributes_cache: {}
Now, lets grab just one of the topics and play around with that:
@topic = Topic.find(1)
You can use the 'y' function on this also. Try this to display certain attributes of @topic:
>> @topic.body
=> "Check it out, http://railsonedge.blogspot.com"
And you can change these attributes pretty easily also:
>> @topic.body = "And now the body says this."
=> "And now the body says this."
>> @topic.body
=> "And now the body says this."
When you change an attribute, it doesn't automatically save it to the database. But not to worry, it is easy enough:
>> @topic.save
=> true
Additionally, if you are working on a project and don't have a create page set up yet for an object yet, you can just create one from the console:
>> topic = Topic.new :body => "Lorem Ipsum",
:subject => "This Subject", :forum_id => 1, :user_id => 1
=> #<Topic id: nil, forum_id: 1, user_id: 1,
subject: "This Subject", body: "Lorem Ipsum",
created_at: nil, updated_at: nil>
>> topic.save
=> true
That is enough for some basic manipulation of things in your database, but what other things can you do with the console? What if you wanted to see all of the functions that can be used on a specific object? Well, just like when you are using bash, you can use tab to auto-complete:
String.to_ [press tab not enter]
String.to_a String.to_s
String.to_enum String.to_yaml
String.to_json String.to_yaml_properties
String.to_param String.to_yaml_style
String.to_query
Another good thing to use the rails console for is to test out little bits of code to see how they run. Here is a simple example using a loop in the console:
>>@topics = Topic.find(:all)
>> for topic in @topics do
?> puts topic.subject + " - append this"
>> end
My Rails 2.0 Forum Tutorial - append this
New Blog Post Today!! - append this
Welcome! - append this
Question: - append this
As with most terminals, you can access your command history by using the up arrow.
Another cool thing, when you are messing around with routing, you can check things out quickly with app.url_for and app.get:
>> app.url_for(:controller => 'forums', :action => 'index')
=> "http://www.example.com/forums"
>> app.get '/forums/1/topics'
=> 200
>> app.get '/invalid/url'
=> 404
The underscore('_') character will return the value of the last statement:
>> 5 + 9
=> 14
>> _
=> 14
>> _ + 6
=> 20
>> _
=> 20
Well, that is it for now. Let me know what other uses you guys (and girls?) have for the console.
Later,
-Ralph
Friday, April 25, 2008
DRY Up Your Views With Layouts For Your Partials
I got comments on my previous post, DRY up your views with nested partials, letting me know that there is a better way. So here is the same thing, done the proper way:
First, I've got this cool set of divs that gives me a nice looking window I will be reusing:
<div id="window-top"></div>
<div id="window">
<%= render :partial => 'mypartial' %>
</div>
<div id="window-bottom"></div>
<div id="window-top"></div>
<div id="window">
<%= render :partial => 'myotherpartial' %>
</div>
<div id="window-bottom"></div>
The goal here is to be able to re-use the code for the window multiple times. First, lets create a partial called '_lorem.html.erb':
<p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum." </p>
And another called '_blah.html.erb':
<p>blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah </p>
Alright! Now, make one last partial, which will be used for the layout, called '_window.html.erb'. Note that it needs to be created in the same directory as the other partials. This is where you put the code for the cool window you just made.
<div id="window-container">
<div id="window-top-left"></div><div id="window-top">Window Title</div>
<div id="window-top-right"></div>
<div id="window">
<%= yield %>
</div>
<div id="window-bottom-left"></div><div id="window-bottom">
</div><div id="window-bottom-right"></div>
</div>
And now, when you want to render a partial that is inside your window, all you need to do is set the layout to window:
<h1>Test of nested partials</h1>
<%= render :partial => 'blah', :layout => 'window' %>
<%= render :partial => 'lorem', :layout => 'window' %>
And thats it! Enjoy DRYing up your views. Later
-Ralph
EDIT: if you use :layout => 'layouts/window', you can put '_window.html.erb' in /views/application and reuse it throughout the site.
Wednesday, April 16, 2008
DRY up your views with nested partials
NOTE: I got a couple of comments letting me know that the proper way to do this is to use a layout with your partial. Please see this post for instructions. Since making this post, I've been told the partial nesting is generally a bad idea, so use at your own risk.
Got a good one for you today that should help clean up your views and DRY things out. How many times, when building a website, do you use the same code over and over again to build this cool looking window that is re-used over and over?
<div id="window-top"></div>
<div id="window">
<%= render :partial => 'mypartial' %>
</div>
<div id="window-bottom"></div>
<div id="window-top"></div>
<div id="window">
<%= render :partial => 'myotherpartial' %>
</div>
<div id="window-bottom"></div>
Well, you can use nested partials to achieve the same effect and re-use your window code. First, lets create a partial called '_lorem.html.erb':
<p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum." </p>
And another called '_blah.html.erb':
<p>blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah </p>
Alright! Now, make one last partial, '_window.html.erb'. This is where you put the code for the cool window you just made.
Inside of it, you want to render a partial, and pass in the variable 'name':
<div id="window-container">
<div id="window-top-left"></div><div id="window-top">Window Title</div>
<div id="window-top-right"></div>
<div id="window">
<%= render :partial => name %>
</div>
<div id="window-bottom-left"></div><div id="window-bottom">
</div><div id="window-bottom-right"></div>
</div>
And now, when you want to render a partial that is inside your window, all you need to do is render the 'window' partial, and as a local
variable named 'name', pass in the name of the partial you want rendered inside of it:
<h1>Test of nested partials</h1>
<%= render :partial => 'window', :locals => {:name => 'lorem' } %>
<%= render :partial => 'window', :locals => {:name => 'blah' } %>
And thats it! Enjoy DRYing up your views with nested partials. Later
-Ralph
Wednesday, April 9, 2008
ActiveScaffold - Helpers for columns with same name overwrite each other - FIX
Really quick one today. I was working on my ActiveScaffold project, and came across the following problem:
My Events table has a column called schools, and so does my Schools table. For the Events, I needed a dropdown box listing all schools...while for Schools, I needed a text box to show up to type in the name of the school. Since textboxes are the default for activescaffold, I shouldn't need to do anything with schools in it, however, when I wrote a form override for Events in event_helper.rb to give it a dropdown box...the dropdown showed up in Schools also. So first, I tried doing a form override in the school_helper.rb. No luck, the event helper method has the same name, and overrides whatever method I put in school with the same name. So to fix it, I removed my helper methods from the event and school helpers. In application_helper.rb, I made a function with the same name as the form override function I had been trying to use, and then used an if to determine which model the helper was being called from. Here is the code:
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
#hack to make activescaffold form overrides work when 2 models have a field that is the same name
def school_form_column(record, input_name)
if record.class.name == "Event"
select_tag input_name, options_for_select(aschools, selected = record.school)
else #record.class.name =="School"
text_field :record, :school, :name => input_name
end
end
private
#used in case of Event
def aschools
@schools = School.find(:all, :order => 'school')
@schooloptions = Hash.new
for school in @schools
@schooloptions[school.school] = school.abbrv
end
@schooloptions = @schooloptions.sort.each { |e| puts "#{e[0]} => #{e[1]}" }
end
end
Me: 2
ActiveScaffold: 0
Done.
Wednesday, April 2, 2008
Rails 2.0 Links
Decided to make a post with links to all the good resources I have come across so far. I'll be putting a permanent link to it on the sidebar. Feel free to leave a comment if you have any links you would like me to add.
RubyPlus.org - Lots of good screencasts; Restful Authentication, AWDR's Depot app for Rails 2.0
Rails Envy - They have a great ActiveRecord intro video here, among other things
Railscasts - Should need no introduction :)
Planet Ruby on Rails - Has feeds from many different Rails blogs all in one convenient place
InstantRails - For you Windows users, this program is a quick way to get up and going with Rails
DanielFischer.comTutorial for using Gmail as a mail server for a Rails project.
Jonathan s ng - ActionMailer Tutorial
Render Examples - Great render examples, helps when needing to render things with AJAX
Absolute Moron's Guide to Forms in Rails - Great form tutorial
Will be adding many more links in the days to come, this is just a preliminary list. Also, I would like to get some links for setting up Rails for development on several OS's(Linux flavors, MAC, ...), so if you have any please leave a comment.
Later.
-Ralph
Tuesday, March 25, 2008
Found a nice ActiveRecord Tutorial
Wish I had found this a couple of months ago, it would have moved me along a lot. I still learned a good deal from it though.
Check it out at:
Rails Envy
-Ralph
Monday, March 24, 2008
Legacy MySQL Database - TinyInt
Apparently Rails typecasts MySQL tinyint's as booleans. I was working on a Rails app for a legacy database today when I realized that I couldn't pull the value out of my 'terms' column. All it would read is a true or false, and not the actual value. After a bit of research, I discovered before_type_cast accessor. So instead of using report.terms, in order to get the value out, I had to use report.terms_before_type_cast.
Short post, but I'm sure someone will have the same problem at some point and will find it helpful.
Later.
-Ralph
Friday, March 21, 2008
Tutorial: Beginning AJAX with Rails 2.0
Today, I'm going to go over a quick tutorial of some basic AJAX functions. Rails has a great implementation with AJAX right out of the box, with the Prototype library. It also includes the Scriptaculous library with some special effects. We are just going to do some basic writing text into the site without page reloading. Lets get started.
Set up the application:
rails ajaxtest -d mysql
cd ajaxtest
./script/generate model Foobar foo:string bar:string
./script/generate Controller Foobars
This is our first project that doesn't use scaffolding - I decided against it because scaffolding would have generated all kinds of views we aren't going to need for this. Notice that when you created the model, it automatically generated your DB migration file. Now, lets open up app/controllers/foobars_controller.rb and do this:
class FoobarsController < ApplicationController
def index
@foobars = Foobar.find(:all)
respond_to do |format|
format.html # index.html.erb
end
end
end
Next, create app/views/foobars/index.html.erb:
<h3>Foobars!</h3>
<table>
<tr><th>Foo</th><th>Bar</th></tr>
<% for foobar in @foobars do %>
<tr>
<td><%= foobar.foo %></td>
<td><%= foobar.bar %></td>
</tr>
<% end %>
</table>
Now lets add our routing. In config/routes.rb add:
map.resources :foobars
In your console, lets get our db created and foobars table setup:
rake db:create
rake db:migrate
And one last thing. We need to populate our table with a few foobars. This is a good time to show you the rails interactive console:
./script/console
From here, we can give commands directly to our project. Lets try one:
Foobar.find(:all)
>> Foobar.find(:all)
=> []
So it returned an empty array. The interactive console is great for playing around with bits of code to see what they do or even testing out bits of code. Lets try another command:
>> myfoobar = Foobar.new
=> #<Foobar id: nil, foo: nil, bar: nil, created_at: nil, updated_at: nil>
>>
Creates a new foobar object...
>> myfoobar.foo = "This is a test."
=> "This is a test."
>> myfoobar.bar = "This is only a test."
=> "This is only a test."
>>
We can set the values of foo and bar for our new foobar, and...
>> myfoobar.save
=> true
>>
We can save it to the database. Lets try looking it up with find...
>> Foobar.find(:all)
=> [#<Foobar id: 1, foo: "This is a test.", bar: "This is only a test.", created_at: "2008-03-21 18:24:46", updated_at: "2008-03-21 18:24:46">]
>>
Great - so far so good. Now lets create a few more foobars:
myfoobar = Foobar.new
myfoobar.foo = "Foo of foobar #2"
myfoobar.bar = "Bar of foobar #2"
myfoobar.save
myfoobar = Foobar.new
myfoobar.foo = "Foo of foobar #3"
myfoobar.bar = "Bar of foobar #3"
myfoobar.save
myfoobar = Foobar.new
myfoobar.foo = "Foo of foobar #4"
myfoobar.bar = "Bar of foobar #4"
myfoobar.save
And done. You can type exit to leave the interactive console. Start the server, browse to localhost:PORT/foobars
Tablespoon of AJAX
First thing, I'm going to tell you that if you don't have Firebug yet, go ahead and get it. It is a plugin for Firefox(you are using firefox, right? nothing against you Safari/Opera lovers..if you are using IE you have no excuses, get Firefox and get Firebug...now). Firebug is a great tool for design as well as for AJAX. The inspect mode will highlight divs under your mouse and show the corresponding html/css code in the panel below. You can also take a look at Javascript AJAX responses and more quickly debug your code. Lets create app/views/layouts/application.html.erb:
<html>
<head>
<%= javascript_include_tag :defaults %>
</head>
<body>
<%= yield :layout %>
</body>
</html>
The include tag will include (among other things) the prototype library that you need to make the AJAX calls. Now, lets head back to app/views/foobars/index.html.erb and set it up for our AJAX. Change it to this:
<h3>Foobars!</h3>
<table>
<tr>
<th>Foo</th>
<th>Bar</th>
<th>Which?</th>
<th>Links</th>
</tr>
<% for foobar in @foobars do %>
<% idstring = "foobar-" + foobar.id.to_s %>
<tr>
<td><%= foobar.foo %></td>
<td><%= foobar.bar %></td>
<td id="<%= idstring %>"></td>
<td>
<%= link_to_remote "Foo", :url =>{ :action => :set, :updatewith => foobar.foo },
:update => idstring %>
<%= link_to_remote "Bar", :url =>{ :action => :set, :updatewith => foobar.bar },
:update => idstring %>
</td>
</tr>
<% end %>
</table>
We have 2 more columns in our table now - Which? will be updated by AJAX with either the foo or the bar of our current Foobar depending on the link clicked from the Links column. In the Links column, we have 2 link_to_remote 's. link_to_remote generates all the javascript calls to send an AJAX request back to our controller on the server. The first argument is what will be displayed for the link. In :url, we define the action to send the request to (:set), as well as the string we want to pass into the function (:updatewith). Last, :update will be the name of the div we will be updating. You can also add another parameter, :position. For example, :position => :before would insert whatever you are sending before the td tag, :after would be after it, :top would insert it inside the td, above anything else, and :bottom inserts it inside the td, at the bottom. If you do not specify a position(like we are doing), it will simply over-write what is inside the div. One more thing to do; lets open up app/controllers/foobars_controller.rb and add in our :set action:
def set
render :text => params[:updatewith]
end
Go back to the page and try clicking the links
Update: I found this link to be very helpful with different ways of using render with AJAX.
And we are done! Thanks for visiting, and see you next time.
Wednesday, March 12, 2008
Using a 'blob' with ActiveScaffold
So I'm using ActiveScaffold to create an admin interface for a site, using a legacy database. It has a table called 'Events', one of the column names is event, of type medium blob, which will only contain text. ActiveScaffold will display the contents of the blob field correctly, but when you go to create a new Event or edit an existing one, it will not give you a text field to enter anything in. Here is the fix:
In app/helpers, I created a file event_helper.rb and put this code in it:
module EventHelper
def event_form_column(record, input_name)
text_field :record, :event, :name => input_name
end
end
And everything worked fine.
Begin Rescue Else End
So today I was working on a project. This project will be an admin interface for an application that has already been running for a while(which was written in PHP). So I am having to use a legacy database(tutorial coming soon for making admin interface for a legacy DB!) Anyway, I have an employee, and a department. The employee references which department he is in by the ID. However, some employees have an ID that is not used in the department table(department got deleted at some point, never existed, who knows?).
In my employee model, I am making a function to take the department id from the employee tables(thisdept), and look up the number in the department table to get the name of the department, all pretty standard stuff.
Here is what I tried first:
def deptname
dept = Department.find(thisdept)
dept.name
end
ActiveRecord::RecordNotFound in Employees#index
Showing vendor/plugins/active_scaffold/frontends/default/views/_list_record.rhtml where line #10 raised:
Couldn't find Department with ID=13
So we are going to need something along the lines of a try - catch. Ruby's equivalent is the begin-rescue-else-end. Begin is the code that might throw an error. Rescue is the code to excute if there is an error. Else is executed if there is no error. You can also add an ensure block, which will be run after everything, regardless. Here is my fix:
def deptname
begin
dept = Department.find(thisdept)
rescue
"No Department"
else
dept.name
end
end
Works like a charm! See you next time.
Monday, March 10, 2008
Rails Forum - Restful Authentication(Part 3 of 3)
NOTE: If you don't want to do Parts 1 and 2, you can download the code for them here, and use this as a stand-alone tutorial. Please note that our Topic and Reply models both belongs_to a user.
I got a lot of this stuff from RubyPlus's RESTful Authentication tutorial. Let's get started!
cd myforum
ruby script/plugin install http://elitists.textdriven.com/svn/plugins/acts_as_state_machine/trunk
ruby script/plugin install http://svn.techno-weenie.net/projects/plugins/restful_authentication
ruby script/generate authenticated user sessions --include-activation --stateful
To break down that last command - authenticated is part of the restful_authentication. user is the model to be generated for the user. sessions will be the controller to handle logging in/out, --include-activation will help with creating the stuff needed to mail an activation link to the user's email, and --stateful is for support for acts_as_state_machine plugin.
Now that our files are generated, let's head to /config/routes.rb and make a couple of changes. Notice that the map.resources :users and map.resources :session lines have already been generated by the generate authenticated call. The version of restful_authentication used in the tutorial on RubyPlus did not automatically generate them.
So in routes.rb:
#CHANGE THIS LINE
map.resources :users
#TO THIS
map.resources :users, :member => { :suspend => :put,
:unsuspend => :put,
:purge => :delete }
#AND THEN ADD THE FOLLOWING LINES
map.activate '/activate/:activation_code', :controller => 'users',
:action => 'activate'
map.signup '/signup', :controller => 'users', :action => 'new'
map.login '/login', :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'
map.forgot_password '/forgot_password', :controller => 'users',
:action => 'forgot_password'
map.reset_password '/reset_password/:id', :controller => 'users',
:action => 'reset_password'
The :member => part sets up some restful actions for the users controller. All the lines that we added sets up named routes for user and session controller/action pairs.
Now, open up /config/environment.rb:
#BELOW THE LINE
Rails::Initializer.run do |config|
#ADD THIS
config.active_record.observers = :user_observer
The observer watches the user model and will be used to send an EMail whenever a new user is created. Next, lets open up /db/migrate/004_create_users.rb and do this.
#OLD 004_create_users.rb
class CreateUsers < ActiveRecord::Migration
def self.up
create_table "users", :force => true do |t|
t.column :login, :string
t.column :email, :string
t.column :crypted_password, :string, :limit => 40
t.column :salt, :string, :limit => 40
t.column :created_at, :datetime
t.column :updated_at, :datetime
t.column :remember_token, :string
t.column :remember_token_expires_at, :datetime
t.column :activation_code, :string, :limit => 40
t.column :activated_at, :datetime
t.column :state, :string, :null => :no, :default => 'passive'
t.column :deleted_at, :datetime
end
end
def self.down
drop_table "users"
end
end
#NEW 004_create_users.rb
class CreateUsers < ActiveRecord::Migration
def self.up
create_table "users", :force => true do |t|
t.string :login, :email, :remember_token
t.string :crypted_password, :limit => 40
t.string :password_reset_code, :limit => 40
t.string :salt, :limit => 40
t.string :activation_code, :limit => 40
t.datetime :remember_token_expires_at, :activated_at, :deleted_at
t.string :state, :null => :no, :default => 'passive'
t.timestamps
end
end
def self.down
drop_table "users"
end
end
There we are just cleaning up the code a little bit. We did add a :password_reset_code column - will be used if a user forgets their password(more on that later). Now just run the migration to create our new tables...
rake db:migrate
Next, open up app/controllers/sessions_controller and copy the line include AuthenticatedSystem to /app/controllers/application.rb. Also, in users_controller, remove the same line. This will make sure that the restful_authentication functions are included on every page.
Now, remove these lines from users_controller in the create function:
self.current_user = @user
redirect_back_or_default('/')
We removed the first line because we do not want to log the user in when they register, we want to verify their EMail. The second line was removed so that Rails would look for create.html.erb after running the create action. Now, create a file /app/views/users/create.html.erb and put something like this in it:
<fieldset>
<legend>Your forum account</legend>
<p>
An EMail has been sent to <%= @user.email %> with instructions to activate
your account.
<li>
If your email is not valid, you must <%= link_to "signup", signup_path %>
again and provide a valid email address.
</li>
<li>
If you don't recieve an email, check your bulk or trash folder, as your spam
filter may have inadvertantly caught the registration email.
</li>
</p>
</fieldset>
Also, create the files app/views/users/change_password.html.erb, app/views/users/forgot_password.html.erb, app/views/users/reset_password.html.erb:
#change_password.html.erb
<% form_for :action => 'change_password' do |f| %>
<fieldset>
<dl>
<dt><label for="old_password" class="block">Old Password</label></dt>
<dd><%= password_field_tag 'old_password', @old_password, :size => 45, :class => 'text' %></dd>
<dt><label for="password" class="block">New Password</label></dt>
<dd><%= password_field_tag 'password', {}, :size => 45, :class => 'text' %>
<div><small>Between 4 and 40 characters</small></div></dd>
<dt><label for="password_confirmation" class="block">Confirm new password</label></dt>
<dd><%= password_field_tag 'password_confirmation', {}, :size => 45, :class => 'text' %></dd>
</dl>
<%= submit_tag 'Change password' %>
</fieldset>
<%end%>
#forgot_password.html.erb
<% form_for :user, :url => {:action => 'forgot_password'} do |form| %>
<fieldset>
<legend>Password Reset Request</legend>
<p>Enter your email address that we have on our file and click send. We will send you a
password reset link email to your email address.</p>
<p>
<label for="user_email" >Email Address:</label><br/>
<%= form.text_field :email, :size => 35, :class => 'text' %>
</p>
<%= submit_tag 'Send' %>
</fieldset>
<% end %>
#reset_password.html.erb
<% form_for :user, :url => {:action => "reset_password"} do |form| %>
<fieldset>
<legend>Reset Password</legend>
<p>
<label for="user_password" >Password</label><br/>
<%= form.password_field :password, :size => 45, :class => 'text' %>
</p>
<p>
<label for="user_password_confirmation" >Confirm Password</label><br/>
<%= form.password_field :password_confirmation, :size => 45, :class => 'text' %>
</p>
<%= submit_tag "Reset your password" %>
</fieldset>
<% end %>
</pre>
<p>Standard stuff there.</p>
<p>Now, open up app/helpers/application_helper.rb and add this code:</p>
<pre>
def user_logged_in?
session[:user_id]
end
We can use this in our views to see if the user is logged in.
Create app/views/layouts/application.html.erb:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-US">
<head>
<title><%= @page_title || 'Rails 2.0 Forum' %></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<%= stylesheet_link_tag 'style' %>
<%= javascript_include_tag :defaults %>
</head>
<body>
<!-- ##### Header ##### -->
<div id="header">
<div class="superHeader">
<% if user_logged_in? %>
<span>You are logged in as: </span>
<%= current_user.login %>
<% else %>
<span>Welcome Guest</span>
<% end %>
</div>
<div class="midHeader">
<h1 class="headerTitle" lang="la">Rails 2.0 Forum</h1>
</div>
<div class="subHeader">
<span class="doNotDisplay">Navigation:</span>
<% if user_logged_in? %>
<%= link_to 'Logout', logout_url %>
<% else %>
<%= link_to "Signup", signup_url %>
| <%= link_to 'Login', login_url %>
<% end %>
| <%= link_to 'Contact Us', 'contact' %>
</div>
</div>
<!-- ##### Main Copy ##### -->
<div id="main-copy">
<% flash.each do |key,value| %>
<div id="flash" class="flash_<%= key %>" >
<span class="message"><%= value %></span>
</div>
<% end -%>
<%= yield :layout %>
</div>
</body>
</html>
And then delete forums.html.erb, replies.html.erb, and topics.html.erb so that only the application.html.erb will show.
Lets go ahead and get some different styling in this. Download this stylesheet and toss it in /public/stylesheets.
Alright! Now we should be able to fire up the server and have a look at what we've got.
Next, open up app/views/sessions/new.html.erb. Uncomment the 'Remember me' section, and then next to the submit button, add:
<%= link_to 'Forgot Password?', forgot_password_url %>
Create /app/views/users/change_password.html.erb:
<% form_for :action => 'change_password' do |f| %>
<fieldset>
<dl>
<dt><label for="old_password" class="block">Old Password</label></dt>
<dd><%= password_field_tag 'old_password', @old_password, :size => 45,
:class => 'text' %></dd>
<dt><label for="password" class="block">New Password</label></dt>
<dd><%= password_field_tag 'password', {}, :size => 45, :class => 'text' %>
<div><small>Between 4 and 40 characters</small></div></dd>
<dt><label for="password_confirmation" class="block">
Confirm new password</label></dt>
<dd><%= password_field_tag 'password_confirmation', {}, :size => 45,
:class => 'text' %></dd>
</dl>
<%= submit_tag 'Change password' %>
</fieldset>
<%end%>
Create /app/views/users/forgot_password.html.erb
<% form_for :user, :url => {:action => 'forgot_password'} do |form| %>
<fieldset>
<legend>Password Reset Request</legend>
<p>Enter your email address that we have on our file and click send. We will
send you a password reset link email to your email address.</p>
<p>
<label for="user_email" >Email Address:</label><br/>
<%= form.text_field :email, :size => 35, :class => 'text' %>
</p>
<%= submit_tag 'Send' %>
</fieldset>
<% end %>
And create /app/views/users/reset_password.html.erb
<% form_for :user, :url => {:action => "reset_password"} do |form| %>
<fieldset>
<legend>Reset Password</legend>
<p>
<label for="user_password" >Password</label><br/>
<%= form.password_field :password, :size => 45, :class => 'text' %>
</p>
<p>
<label for="user_password_confirmation" >Confirm Password</label><br/>
<%= form.password_field :password_confirmation, :size => 45, :class => 'text' %>
</p>
<%= submit_tag "Reset your password" %>
</fieldset>
<% end %>
We are moving kind of fast here, but most of this stuff should make sense to you, you just need to see it in action. If you have any questions over how anything works, leave a comment and I will get back to you.
Now, in app/controllers/users_controller.rb, lets add in the actions for forgot_password, reset_password, and change_password:
def change_password
return unless request.post?
if User.authenticate(current_user.login, params[:old_password])
if ((params[:password] == params[:password_confirmation]) &&
!params[:password_confirmation].blank?)
current_user.password_confirmation = params[:password_confirmation]
current_user.password = params[:password]
if current_user.save
flash[:notice] = "Password successfully updated"
redirect_to profile_url(current_user.login)
else
flash[:alert] = "Password not changed"
end
else
flash[:alert] = "New Password mismatch"
@old_password = params[:old_password]
end
else
flash[:alert] = "Old password incorrect"
end
end
#gain email address
def forgot_password
return unless request.post?
if @user = User.find_by_email(params[:user][:email])
@user.forgot_password
@user.save
redirect_back_or_default('/')
flash[:notice] = "A password reset link has been sent to your email address"
else
flash[:alert] = "Could not find a user with that email address"
end
end
#reset password
def reset_password
@user = User.find_by_password_reset_code(params[:id])
return if @user unless params[:user]
if ((params[:user][:password] && params[:user][:password_confirmation]) &&
!params[:user][:password_confirmation].blank?)
self.current_user = @user #for the next two lines to work
current_user.password_confirmation = params[:user][:password_confirmation]
current_user.password = params[:user][:password]
@user.reset_password
flash[:notice] = current_user.save ? "Password reset success." : "Password reset failed."
redirect_back_or_default('/')
else
flash[:alert] = "Password mismatch"
end
end
In config/environments/development.rb you need to add SITE="http://localhost:3000" at the bottom, we will get to this in just a sec.
Now we will take a look at the user_mailer views. They are used to format emails sent out to users. In app/views/user_mailer/activation.html.erb, remove the part where it says "You may now start adding your plugins:". Now lets create app/views/user_mailer/forgot_password.html.erb, and app/views/user_mailer/reset_password.html.erb:
#forgot_password.html.erb
Dear <%= @user.login %>,
We have had a request to reset your password, please visit
<%= @url %>
#reset_password.html.erb
Your have reset the password for your account successfully.
Username: <%= @user.login %>
Password: <%= @user.password %>
Now lets edit app/models/user.rb. Near the bottom, somewhere after the protected keyword, add the follow function:
def make_password_reset_code
self.password_reset_code = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
end
And then above protected, add these functions:
def forgot_password
@forgotten_password = true
self.make_password_reset_code
end
def reset_password
# First update the password_reset_code before setting the
# reset_password flag to avoid duplicate email notifications.
update_attributes(:password_reset_code => nil)
@reset_password = true
end
#used in user_observer
def recently_forgot_password?
@forgotten_password
end
def recently_reset_password?
@reset_password
end
def recently_activated?
@recent_active
end
And now we need to set up the user_mailer model to use all of this. Change app/models/user_mailer.rb to look like this:
class UserMailer < ActionMailer::Base
def signup_notification(user)
setup_email(user)
@subject += 'Please activate your new account'
@body[:url] = "#{SITE}/activate/#{user.activation_code}"
end
def activation(user)
setup_email(user)
@subject += 'Your account has been activated!'
@body[:url] = "#{SITE}/"
end
def forgot_password(user)
setup_email(user)
@subject += 'You have requested to change your password'
@body[:url] = "#{SITE}/reset_password/#{user.password_reset_code}"
end
def reset_password(user)
setup_email(user)
@subject += 'Your password has been reset.'
end
protected
def setup_email(user)
recipients "#{user.email}"
from %("Rails Forum Admin") # Sets the User FROM Name and Email
subject "[Rails Forum] New account information "
body :user => user
sent_on Time.now
end
end
Note where we used the SITE constant that we set in development.rb earlier. Lets stop the server and then restart it since we changed the development.rb. Now, we should be able to go back and sign up.
If you check the console running your server, you will see SQL queries adding the new user to the database, and the email being sent(it won't actually send an email since we are in development)
Go to think link from the console(localhost:3000/activate/whatever) and you will get a message saying 'Signup complete' and you will be logged in. It will also send an email saying that your account has been activated. You can test everything by logging out and logging back in again.
Alright, we are almost done! Next, open up app/models/user_observer.rb and change the after_save function to this:
def after_save(user)
UserMailer.deliver_activation(user) if user.recently_activated?
UserMailer.deliver_forgot_password(user) if user.recently_forgot_password?
UserMailer.deliver_reset_password(user) if user.recently_reset_password?
end
Just more setting up for the mailer.
So, now we have a Signup, a few ways for taking care of forgotten passwords, and email authentication. But how do we block the adding posts and replies to only people logged in? How do we restrict creating forums and deleting posts to only an admin? Open up the file vendor/plugins/restful_authentication/generators/authenticated/templates/authenticated_system.rb and read through some of the comments about the functions:
# Returns true or false if the <%= file_name %> is logged in.
# Preloads @current_<%= file_name %> with the <%= file_name %> model if they're logged in.
def logged_in?
current_<%= file_name %> != :false
end
# Accesses the current <%= file_name %> from the session. Set it to :false if login fails
# so that future calls do not hit the database.
def current_<%= file_name %>
@current_<%= file_name %> ||= (login_from_session || login_from_basic_auth || login_from_cookie || :false)
end
logged_in? checks the value of current_user and returns true if it does not equal :false. current_user tries to login from a session, from basic auth, and from a cookie. If it is unable to log them in, it will return :false and cause the value of logged_in to be false.
# Check if the <%= file_name %> is authorized
#
# Override this method in your controllers if you want to restrict access
# to only a few actions or if you want to check if the <%= file_name %>
# has the correct rights.
#
# Example:
#
# # only allow nonbobs
# def authorized?
# current_<%= file_name %>.login != "bob"
# end
def authorized?
logged_in?
end
# Filter method to enforce a login requirement.
#
# To require logins for all actions, use this in your controllers:
#
# before_filter :login_required
#
# To require logins for specific actions, use this in your controllers:
#
# before_filter :login_required, :only => [ :edit, :update ]
#
# To skip this in a subclassed controller:
#
# skip_before_filter :login_required
#
def login_required
authorized? || access_denied
end
We can use before_filter :login_required to stop people from going to /topic/1/posts/2/edit and being able to edit the post. logged_in? can be used in forum and topic's show views, to stop the form for new topics and replies from being shown. This can all be setup however you want, there are plenty of possibilities. What I am going to do is show you how to display different things based on who is logged in, and how to limit certain actions in your controllers. That should give you enough to figure out what you want to do for your specific application. First, open up app/views/forums/show.html.erb:
#find these 3 lines
<h2>New Post</h2>
<%= render :partial => @topic = Topic.new, :locals => { :button_name => 'Create' } %>
<%= link_to 'New Topic', new_forum_topic_path(@forum) %> |
#and put this around them
<% if logged_in? %>
<h2>New Post</h2>
<%= render :partial => @topic = Topic.new, :locals => { :button_name => 'Create' } %>
<%= link_to 'New Topic', new_forum_topic_path(@forum) %> |
<%end>
#and then change this line
<%= link_to 'Edit', edit_forum_path(@forum) %> |
#to this
<% if is_admin? %>
<%= link_to 'Edit', edit_forum_path(@forum) %> |
<% end %>
And now, go to app/controllers/application.rb. In this file we can write functions that will be available to all controllers. Add this to it:
helper_method :is_admin?
def is_admin?
if logged_in? && current_user.login == "admin"
true
else
false
end
end
def admin_required
is_admin? || admin_denied
end
def admin_denied
respond_to do |format|
format.html do
store_location
flash[:notice] = 'You must be an admin to do that.'
redirect_to forums_path
end
end
end
The first line, helper_method :is_admin? will let this function be used in the view. current_user.login is the username for the person logged in. You can change this method however you want to determine whether or not a user is an admin. admin_required and admin_denied will be used in our controllers to restrict access to actions - lets go to our app/controllers/forums_controller.rb and put that in:
#at the very top, right after class ForumsController < ApplicationController, add this line:
before_filter :admin_required, :only => [ :edit, :update, :create, :new, :destroy ]
Now, when you try to access edit, update, create, new, or destroy actions in your controller, if your username is not 'admin', it will go to the show forums page and have a flash saying 'You must be an admin to do that'.
Well, I guess that is it for now. We've added the ability to create users, reset passwords, verify email, and restrict actions to admins. This isn't a completely finished web app. We didn't look into any kind of input validation and we didn't go over all the things we would need to limit to users logged in(create post and create reply), and we didn't limit a lot of things to admins that we should have(such as editing and destroying posts/replies). Hopefully, you've learned enough from this to be able to figure it out yourself, but if you have any trouble feel free to leave a comment. Also, let me know if there are any typos, mistakes, or questions about the tutorial, as well if you have any suggestions. Thanks for reading!
-Ralph
Monday, February 25, 2008
Rails Forum Tutorial for Beginners(Part 2 of 3)
The nesting in /config/routes.rb has already been taken care of in the first tutorial:
map.resources :topics, :has_many => :replies
The first thing we are going to do is to create partials for /app/views/replies/new.html.erb and /app/views/replies/edit.html.erb. Create the file /app/views/replies/_reply.html.erb
#/app/views/replies/_reply.html.erb
<% form_for([@topic, @reply]) do |f| %>
<p>
<b>Subject</b><br />
<%= f.text_field :subject %>
</p>
<p>
<b>Body</b><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit button_name %>
</p>
<% end %>
And now change edit and new to:
#/app/views/replies/edit.html.erb
<h1>Editing reply</h1>
<%= error_messages_for :reply %>
<%= render :partial => @reply, :locals => { :button_name => "Submit" } %>
<%= link_to 'Show', [@topic, @reply] %> |
<%= link_to 'Back', replies_path %>
#/app/views/replies/new.html.erb
<h1>New reply</h1>
<%= error_messages_for :reply %>
<%= render :partial => @reply, :locals => { :button_name => "Reply" } %>
<%= link_to 'Back', replies_path %>
Same stuff we did last time...
Now lets go to /app/controllers/replies_controller.rb
Add this at the top, to make sure a topic gets loaded everytime the replies controller is used:
before_filter :load_topic
def load_topic
@topic = Topic.find(params[:topic_id])
end
inside the new function change the line:
@reply = Reply.new
to this:
@reply = @topic.replies.build
Change the edit function:
#old edit function
def edit
@reply = Reply.find(params[:id])
end
#new edit function
def edit
@reply = @topic.replies.find(params[:id])
end
Change the create function:
#old create
def create
@reply = Reply.new(params[:reply])
respond_to do |format|
if @reply.save
flash[:notice] = 'Reply was successfully created.'
format.html { redirect_to(@reply) }
format.xml { render :xml => @reply, :status => :created, :location => @reply }
else
format.html { render :action => "new" }
format.xml { render :xml => @reply.errors, :status => :unprocessable_entity }
end
end
end
#new create
def create
@reply = @topic.replies.build(params[:reply])
respond_to do |format|
if @reply.save
flash[:notice] = 'Reply was successfully created.'
format.html { redirect_to([Forum.find(@topic.forum_id), @topic]) }
format.xml { render :xml => @reply, :status => :created, :location => @reply }
else
format.html { render :action => "new" }
format.xml { render :xml => @reply.errors, :status => :unprocessable_entity }
end
end
end
Notice the change in redirect_to...after a reply to a topic is submitted, I want to send the user back to the forum the topic was in, to get the forum, I had to use the find function and pass it the forum_id of the topic and the topic.
In the update and destroy functions:
#old update and destroy
def update
@reply = Reply.find(params[:id])
respond_to do |format|
if @reply.update_attributes(params[:reply])
flash[:notice] = 'Reply was successfully updated.'
format.html { redirect_to(@reply) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @reply.errors, :status => :unprocessable_entity }
end
end
end
def destroy
@reply = Reply.find(params[:id])
@reply.destroy
respond_to do |format|
format.html { redirect_to(replies_url) }
format.xml { head :ok }
end
end
#new update and destroy
def update
@reply = @topic.replies.find(params[:id])
respond_to do |format|
if @reply.update_attributes(params[:reply])
flash[:notice] = 'Reply was successfully updated.'
format.html { redirect_to(@topic) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @reply.errors, :status => :unprocessable_entity }
end
end
end
def destroy
@reply = @topic.replies.find(params[:id])
@reply.destroy
respond_to do |format|
format.html { redirect_to(@topic) }
format.xml { head :ok }
end
end
Now that we have all of that done...lets head over to /app/views/topics/show.html.erb so we can display our replies and the form for a new reply.
In addition to showing replies and a form for a new one, I changed the formatting a little, so here are the contents on show.html.erb
<p>
<h3>Forum: - <%=h @forum.name %></h3>
</p>
<p>
<b><%=h @topic.subject %></b>
</p>
<p>
<%=h @topic.body %>
</p>
<% unless @topic.replies.empty? %>
<% @topic.replies.each do |reply| %>
<p>
<b><%= reply.subject %></b>
</p>
<p>
<%=h reply.body %>
</p>
<% end %>
<% end %>
<h2>Reply</h2>
<%= render :partial => @reply = Reply.new, :locals => { :button_name => 'Reply' } %>
<%= link_to 'Edit', edit_forum_topic_path(@forum, @topic) %> |
<%= link_to 'Back', topics_path %>
Since this is the same stuff we were doing in the first tutorial, I won't bother explaining any of it...you should be able to tell what is going on. Feel free to leave a comment if you do have any questions.
Now, fire up the web server and head to localhost:3000/forums/1/topics/1 (assuming you have a topic already created).
And create a couple of replies:
And thats it! (10 points go to anyone who catches the video game reference in reply #2 in the screenshot).
In this tutorial, we nested replies inside of a topic, and set the views/controllers accordingly. Next time, we will take a look at authentication using the RESTful authentication plug-in and acts_as_state_machine plugin.
Feel free to leave comments, and link me from your site. See you next time!