Meanwhile I have come across a wonderful learning resource on Rails 3 which I would like to share with everyone. It seems to be quite good to get your feet wet on Rails 3 :
Ruby on Rails Tutorial
Learn Rails by ExampleBy : Michael Hartl
gem install twitter
ruby script/generate controller twitter_publishNow add the following code to your newly created 'TwitterPublishController'
Controller TwitterPublish < ApplicationController
require 'rubygems'
require 'twitter'
def tweet
httpauth = Twitter::HTTPAuth.new('twitter_username', 'password')
@user = Twitter::Base.new(httpauth)
end
endIn the above controller code, provide the required twitter login details.<% @ user.friends_timeline.each do |tweet| %>
<%= image_tag "#{tweet.user[:profile_image_url]}" %>
<%= tweet.user[:screen_name] %> <br/>
<%= tweet.text %><br/>
<% end %>Now if we run the server, and check out the link http://localhost:3000/twitter_publish/tweets , we will find all the latest tweets from the people I am following will be listed down along with their image.<% form_for :twitter do |t| %> What's happening ? <%= t.text_field :tweet %><br/> <%= t.submit "Tweet" %> <% end %>And to create the update we send as tweet through the text field, we have to add the following code to our tweet method in TwitterpublishController:
if request.post? @user.update(params[:twitter][:tweet]) redirect_to :action=>'tweet' endThat's all, you can now tweet directly from your rails application.
class UserSession < Authlogic::Session::Base
validate :check_if_verified
private
def check_if_verified
errors.add(:base, "You have not yet verified your account") unless attempted_record && attempted_record.verified
end
end class AddVerifiedToUser < ActiveRecord::Migration
def self.up
add_column :users, :verified, :boolean, :default => false
end
def self.down
remove_column :users, :verified
end
end def create
@user = User.new(params[:user])
if @user.save
@user.deliver_user_verification_instructions!
flash[:notice] = "Registration verification email sent.Please verify your account."
redirect_to root_url
else
render :action => "new"
end
end def deliver_user_verification_instructions!
reset_perishable_token!
Notifier.deliver_user_verification_instructions(self)
end def user_verification_instructions(user)
subject 'User verification instructions'
recipients user.email
from 'XYZ Notifications'
sent_on Time.now
@body[:url] = "http://test.domain.com/user_verifications/show/#{user.perishable_token}"
end You have created an account for http://domain.com Please follow the link below to verify your account and get started with XYZ <%= @url %> If the above URL does not work try copying and pasting it into your browser. If you continue to have problem please feel free to contact us.
class UserVerificationsController < ApplicationController
before_filter :load_user_using_perishable_token
def show
if @user
@user.verify!
flash[:notice] = "Thank you for verifying your account. You may now login."
end
redirect_to root_url
end
private
def load_user_using_perishable_token
@user = User.find_using_perishable_token(params[:id])
flash[:notice] = "Unable to find your account." unless @user
end
end def verify!
self.verified = true
self.save
end That is it. On successful verification, the verified field gets a value of one and thus, user will be able to log in. So have you guys tried any other ways of doing this. Please share your ideas with me.
Loading development environment (Rails 2.3.5)
>> date = Date.today
=> Fri, 29 Jan 2010
>> start_date = Date.parse "#{date.year}-#{date.month}-01"
=> Fri, 01 Jan 2010
>> last_date = (start_date >> 1)-1 => Sun, 31 Jan 2010
>> start_date.wday => 5
>> ['Cat', 'Dog', 'Bird'].include? 'Dog' => true
gem install authlogicAfter installing the gem, we will be creating a very simple rails application just to test the user authentication functionality via authlogic gem.
C:\>rails user_authentication_demo -d mysqlafter the application is created, lets just go ahead and create a dummy controller dummy method in the controller and a dummy view. This is just to have a page up and running where we will be displaying the working of user authentication functionality.
C:\user_authentication_demo>ruby script/generate controller home indexYou can add some dummy text in your app/views/index.html.erb file just for fun. Working on rails, you got enough time for fun stuffs !
development:
host: localhost
adapter: mysql
database: user_authentication_demo_development
port: 3307
username: root
password:
test:
host: localhost
adapter: mysql
production:
host: localhost
adapter: mysql
C:\user_authentication_demo>ruby script/generate model userAfter all the associated files are created, we will edit the migration file at db/migrate/20100103124423_create_users.rb and ad the following codes in it.
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :username
t.string :email
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.timestamps
end
end
def self.down
drop_table :users
end
end
AuthLogic can pretty much handle fields called email, crypted_password, password_salt and persistence_token and hence we need not bother much about them So let's go ahead and run rake to create the database tables C:\user_authentication_demo>rake db:migrateNext we will have to edit the app/models/user.rb file and add the following codes in it
class User < ActiveRecord::Base acts_as_authentic endThis is to add the Authlogic to the class, without which it will be just a standard model class. Our next task is to create users controller. Also we require new and edit views, and hence we will make sure to create them through generators by the following command
C:\user_authentication_demo>ruby script/generate controller users new editNext we need to modify config/routes.rb file a bit and add the following line of code
map.resources :usersNow inorder to display the link for "Register" , in all the pages of your application add the following lines in your app/views/layouts/application.html.erb file(If you dont have application.html.erb file, then create it)
Next add the following bunch of code in app/controllers/user_controller.rb<%= link_to "Register", new_user_path %><%= yield %>
class UsersController < ApplicationController def new @user = User.new end def create @user = User.new(params[:user]) if @user.save flash[:notice] = "Registration successful." redirect_to :controller=>"blog" else render :action => 'new' end end def edit end endWe will be putting the code for registration in a partial as we will require it for registration as well as editing. So create a patial file in app/views/users/_user.html.erb and add the following codes in it.
<% form_for @user do |form| %> <%= form.error_messages %>And then add the following code in the app/views/users/new.html.erb to call the partial for registration purpose<% end %>
- <%= form.label :username, "Username" %> <%= form.text_field :username %>
- <%= form.label :email, "Email" %> <%= form.text_field :email %>
- <%= form.label :password, "Password" %> <%= form.password_field :password %>
- <%= form.label :password_confirmation, "Password confirmation" %> <%= form.password_field :password_confirmation %>
- <%= form.submit "Submit" %>
<%= render @user %>Now if we check http://localhost:3000/blog we will see the "register" link and if we click on the link, we will be taken to the registration form. If we click on the register button without entering any details, we will get the validation errors and if we enter valid data and then register we will be redirected to blog page. So far so good. next we will add a "Login" link next to "registration" link to let our users to login to the application. For this we have to create UserSession model to get the current status of our users. From the command line,
C:\user_authentication_demo>ruby script/generate session user_sessionThis generator will create UserSession model and this model will be just have an empty class. Next we generate controller for the UserSession
C:\user_authentication_demo>ruby script/generate controller UserSessionsAnd add the following codes within the UserSessions Controller
class UserSessionsController < ApplicationController
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash[:notice] = "Successfully logged in."
redirect_to :controller=>"blog"
else
render :action => 'new'
end
end
def destroy
@user_session = UserSession.find
@user_session.destroy
flash[:notice] = "Successfully logged out."
redirect_to :controller=>"blog"
end
end
Next create a view file in app/views/user_sessions/new.html.erb and add the following codes <% form_for @user_session do |form| %> <%= form.error_messages %>We will have to edit the config/routes.rb a bit to add the following codes.<% end %>
- <%= form.label :username, "Username" %> <%= form.text_field :username %>
- <%= form.label :password, "Password" %> <%= form.password_field :password %>
- <%= form.submit "Submit" %>
map.login 'login', :controller => 'user_sessions', :action => 'new' map.logout 'logout', :controller => 'user_sessions', :action => 'destroy' map.resources :user_sessionsWe can also modify our application.rhtml file to add the link for login
Now if we check our blog page along with "Register" link we also ha "Login" link and if we click on "Login", we will be taken to a Login page with fields for username and password. Upon valid username and password entry, we will be taken to blog page with a flash message. On invalid login details, we will end up with validation errors. Our next aim is to write code for logging out and display "Edit Profile" and "Logout" Links for the logged in users. So let us modify the application.rhtml and have the following codes in there:<%= link_to "Register", new_user_path %> | <%= link_to "Log in", login_path %>
And also add the following code in the app/controllers/application_controller.rb<% if current_user %> <%= link_to "Edit profile", edit_user_path(:current) %> <%= link_to "Logout", logout_path %> <% else %> <%= link_to "Register", new_user_path %> <%= link_to "Log in", login_path %> <% end %><%= yield %>
class ApplicationController < ActionController::Base
helper_method :current_user
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
@current_user = current_user_session && current_user_session.record
end
end
To make the "Edit profile" working modify the user_session controller to class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "Registration successful."
redirect_to :controller=>"blog"
else
render :action => 'new'
end
end
def edit
@user = current_user
end
def update
@user = current_user
if @user.update_attributes(params[:user])
flash[:notice] = "Successfully updated profile."
redirect_to :controller=>"blog"
else
render :action => 'edit'
end
end
end
And then we have to call the form partial by adding the following code within /app/views/users/edit.html.erb <%= render @user %>
gem install prawn
C:\>rails pdf_demo -d mysql
C:\>cd pdf_demo
C:\pdf_demo>ruby script/plugin install http://github.com/thorny-sun/prawnto.git/
config.gem 'prawn'within "Rails::Initializer.run do |config|"
C:\pdf_demo>ruby script/generate controller Book
exists app/controllers/
exists app/helpers/
create app/views/book
exists test/functional/
create test/unit/helpers/
create app/controllers/book_controller.rb
create test/functional/book_controller_test.rb
create app/helpers/book_helper.rb
create test/unit/helpers/book_helper_test.rb
C:\pdf_demo>ruby script/generate model book
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/book.rb
create test/unit/book_test.rb
create test/fixtures/books.yml
create db/migrate
create db/migrate/20091211170948_create_books.rbclass CreateBooks < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.string :name
t.string :author
t.timestamps
end
end
def self.down
drop_table :books
end
end
development: adapter: mysql encoding: utf8 reconnect: false database: pdf_demo_development pool: 5 username: root password: host: localhost
C:\>mysql -u root
C:\>mysql -u root -p (password)
mysql> CREATE DATABASE pdf_demo_development;
C:\pdf_demo>rake db:migrate (in C:/pdf_demo) == CreateBooks: migrating ==================================================== -- create_table(:books) -> 0.0630s == CreateBooks: migrated (0.0630s) ===========================================
mysql> use pdf_demo_development;
mysql> INSERT INTO books (name,author) VALUES ("The Rails Way", "Obie Fernandez");
Query OK, 1 row affected (0.06 sec)
mysql> INSERT INTO books (name,author) VALUES ("Agile Web Development with Rails", "David");
Query OK, 1 row affected (0.01 sec)
class BookController < ApplicationController
def index
end
def show
@book = Book.find(:all)
respond_to do |format|
format.pdf { render :layout => false }
end
end
end
<%= link_to "(PDF Report)", :controller=>"book", :action=>"show", :id=>"2", :format=>'pdf' %>
pdf.move_down(30)
books = @book.map do |item|
[
item.name,
item.author
]
end
pdf.table books, :border_style => :grid,
:row_colors => ["FFFFFF", "DDDDDD"],
:headers => ["book", "author"],
:align => { 0 => :left, 1 => :right, 2 => :right, 3 => :right }
C:\pdf_demo>ruby script/server