29 January 2010

Generating Calendar With Rails

Download the source code from GitHub

Working on a Rails CMS based project using BrowserCMS, there was a requirement to have a page which would display a calendar for the current month and onClick of each date, it has to make an Ajax request to query the database table and update a portion on the same page.

Everything is fine with the requirement, but a Rails calendar with each date sending an Ajax request to the controller?

My initial move was to look for some Rails plugin which would serve this purpose. Had a thorough Google search on this. Time was ticking, I managed to find one or two Rails calendar Plugin, but when tried on my project, it did not serve the exact purpose of each date sending the Ajax request. No much help was there on this in any Rails based forum as well.

This finally made me to think of writing the code for generating the calendar of my own. It was indeed going to be a tough task. But I had no other choice left in-front of me.

I have shared the code for the same through my GitHub account.

There in the GitHub repository you will find only a controllers folder and a views folder. Well that's all we need to get this done. If you have a Rails project up and running, you can go ahead and generate this Calendar Controller and use the code and modify it, style it as per your own requirement.

Here what I have done is, in the "calendar index" page you can see the calendar for the current month, with links for next and previous months, so that you can have a view of all the months. When you click on the next/previous links, the months partial is being updated. Similarly, onClick of each date will update a test "div" with the value of month and date. You can apply any logic here and make it work for your purpose.


Ruby/Rails Tips for the day:

=>How to get the starting day of the month ?

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

=>How to get the last day of the month ?

>> last_date = (start_date >> 1)-1
=> Sun, 31 Jan 2010

=>How to get the weekday of a particular date?

>> start_date.wday
=> 5

Special thanks to Nithin Bekal who helped me in getting this work done in no time.
If anyone uses this code for their application, please share with me the improvements made.

26 January 2010

Custom Blog Post Reordering In WordPress

Wordpress is no doubt one of the best CMS around and with the awesome community out there contributing in all ways to make it the best of the best is really appreciative.

Well, few days back working on a wordpress project for a client, The client came up with some requirement and that was like, he would like to manually rearrange the Posts the way he wants and not the default date ordering of Wordpress.

But I had never heard about custom post order ever before untill the client mentioned about it and that made me look for the right plugin which would make this work out for me. And guess what, I came up with nearly 3 plugins which would serve the purpose.

I installed it on my test domain and checked it out. Whohooo! they worked and I settled with a plugin named Blog Reordering.

Installed it in the client's domain and then on client request documented the best way to use this plugin to reorder the posts and drafted a mail to him. Here's the mail which I prepared for the client:

As you want the posts to be reordered manually and do not want them to show up according to the date and time settings, We have a plugin named Post Reorder which will help us to the stuff of custom reordering of posts as we want.

Well, As it gives you the freedom to custom reorder the posts, Its kind of a manual work to reorder the posts as well.

And here's how you can achieve it:

1.Navigate to Blog Reordering section which is at the very bottom Settings in admin page of the wordpress.

2.Here you can find options such as "Blog reordering Settings", "Quick reorder by field" and "Blog reordering"

3. Let the first two option be as it is.

4. We need to worry only about the third option and that is where all reordering stuff takes place.

5.Here you can find all the posts listed down with the "ordering" numbed 1,2,....etc to the latest post you have up to date.

6.Now its all manual task, where you have to identify the right posts of each category and number them in the order you want.

For example:

You have 25 posts in personal category and all the 25 are randomly ordered and ordering number is also random according to the order they were posted.

Well, you need not worry about the random order each of the 25 posts of "personal" category has got, you can just go ahead and number them from 1 to 25 in the order you want them to display and that's it. When you check out the personal category page, all the 25 posts will be ordered the way you have set them. Now that's called absolute freedom!

Well, if there is no name to each of your posts, then it is kind of hectic knowing which posts is which one and the only option is to identify them via their ID's.

That's all about it. Did I miss anything relevant about this plugin ? Please do share it with me.

Thanks

25 January 2010

Share Source Code Using GitHub- It's Social Coding!

Done writing the codes of your current project? And is excited about it and want the whole developer community to know about your latest project? Then Lets Git It!

Yes, I am also equally excited about my latest project and I wanted it to share with the developer community through GitHub-Social Coding!

The application was developed using Ruby On Rails and hence the hosting provider is HostingRails. So I have my application running up there. So all I had to do was commit the source code from HostingRails into the GitHub repository.

I will be explaining the exact procedure that I followed to commit the source code of my application into GitHub repository directly from HostingRails.
I use PuTTy which is an open source telnet and SSH Client for the Windows and Unix platforms.

Since my application was hosted in HostingRails, I logged into it via PuTTy and I was taken into my root folder. If you are not aware of PuTTy interface, then I would say it is just a Unix Terminal for you to work on. So from the root folder I had to get in my project folder which I did using CD command.

Well before we do anything , a GitHub account is necessary or else where are we going to commit all our source code! So I did create a GitHub Account and I am all set for Social Coding.

Next I had to create a New repository.(See Images)








Once I provided all the information for creating the repository, I hit create-repository. And that's all. After I created the repository, I was redirected to the new repository page which had the basic information on how to commit the source codes.

here's what i did for committing the source code for my application.

In PuTTy, as i was already in my application folder:

email@email.com [~/rails/My_Project]#

Next i had to initialize the git in my application:


email@email.com [~/rails/My_Project]#git init
Initialized empty Git repository in /home/fedenac/rails/testing/.git/

Once initialized, I had to include all the folders and files.

email@email.com [~/rails/My_Project]#git add .

And after that commit it


email@email.com [~/rails/My_Project]#git commit -m 'any message here'

Then I had to add the remote origin


email@email.com [~/rails/My_Project]#git remote add origin git@github.com:techslam/test.git

In the above command "git@github.com:techslam/test.git" is the URl which we find at the top of the page after successfully creating the repository.(See Image)



And finnaly we push it:


email@email.com [~/rails/My_Project]#git push origin master

And that's it. When I checked my repository all my source code was ready to be shared with the wonderful development community out there.

So Folks, what's your say on GitHub feature. I am really enjoying it and is going to explore it deeper and deeper.

16 January 2010

David Heinemeier Hansson of 37signals at FOWA Dublin 2009


David Heinemeier Hansson - FOWA Dublin 2009 from Carsonified on Vimeo.


David Heinemeier Hansson discusses the prospects of starting a business in “The Real World”. David explains that “The Real World” is filled with naysayers that say your idea won’t work. The first thing that an entrepreneur should do is ignore “The Real World”. David takes down the many myths of “The Real World” while sharing his successes in the face of all the naysayers.

For more of such talks check out 37Signals-Speaks

10 January 2010

Moving along with BrowserCMS

As I have mentioned in one of my previous posts that, the project I am associated at present deals with setting up a Content management System using BrowserCMS. Its been quite a some time I am involved in this project and in the mean time learnt a lot about this CMS. The best part is that, the CTO of BrowserMedia Mr.Patrick Peak would answer to any of your doubts related to BrowserCMS. I have had a lot of questions related to BCMS and most of them were answered by him in a matter of day. So Iam really thankful to him and really appreciate the work he has been doing.

This project is taking quite a bit of time to get it completed because of some special requiremnts from the client like setting up Multi Language functionality. Though BrowserCMS don't have a built in support for i18n(As told by Mr.Patrick Peak,CTO BrowserMedia), It was a huge challenge for me to bring some unique concept of Multi Language functionality in Browser CMS. Well, I did make a quite a bit of research on this and finally came up with indeed a unique concept to get this requirement done.
The concept has been explained to our client and is waiting to get his approval.

In the coming posts you can expect, the Idea behind setting up the Multi Language Functionality using browser CMS. So stay tuned. Till then CiaO

Ruby Tip of the day:

To check if there is an item in an array...
>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

03 January 2010

User Authentication in Rails : AuthLogic

Working on any web application, there is always a need to have user authentication system running in the application. Ruby on Rails is blessed to have a such an active community which always comes up with solutions to rails of any kind. For user authentication there is an awesome plugin called AuthLogic. I have used this plugin in an application I am currently associated with and it works like a charm.

In this post you can find step by step instruction on getting this plugin up and running in your application.

Installing AuthLogic

AuthLogic can either be installed as a plugin or as a gem. I would rather go with installing a gem. So from the command line:
gem install authlogic
After installing the gem, we will be creating a very simple rails application just to test the user authentication functionality via authlogic gem.

So from command line create a new application named user_authentication_demo
C:\>rails user_authentication_demo -d mysql
after 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.

So create a controller by:
C:\user_authentication_demo>ruby script/generate controller home index
You 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 !
(Make sure you have <%= flash[:notice] %> in there to get the flash messages)

Next open up the config/database.yml find athen replace the entire content here with the following code
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

All I have done is removed unwanted junk of codes from there to keep it straight and simple.

Now if we run the server and go to http://localhost:3000/blog, we will be taken to the dummy page as shown below:



We will be adding the user authentication to the above page. In this page we will be showing "Register","Login" links if the user is not logged in and "Edit Profile","Logout" links if the user is logged in.

Next we need to create Model and Controller for Users. First we will be generating our User Model
C:\user_authentication_demo>ruby script/generate model user
After 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:migrate
Next 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 
end
This 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 edit
Next we need to modify config/routes.rb file a bit and add the following line of code
map.resources :users  
Now 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)
<%= link_to "Register", new_user_path %>
<%= yield %>
Next add the following bunch of code in app/controllers/user_controller.rb
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

end
We 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 %>  
 

  1. <%= form.label :username, "Username" %> <%= form.text_field :username %>
  2. <%= form.label :email, "Email" %> <%= form.text_field :email %>
  3. <%= form.label :password, "Password" %> <%= form.password_field :password %>
  4. <%= form.label :password_confirmation, "Password confirmation" %> <%= form.password_field :password_confirmation %>
  5. <%= form.submit "Submit" %>
<% end %>
And then add the following code in the app/views/users/new.html.erb to call the partial for registration purpose
<%= 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_session
This 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 UserSessions
And 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 %>  
 

  1. <%= form.label :username, "Username" %> <%= form.text_field :username %>
  2. <%= form.label :password, "Password" %> <%= form.password_field :password %>
  3. <%= form.submit "Submit" %>
<% end %>
We will have to edit the config/routes.rb a bit to add the following codes.
map.login 'login', :controller => 'user_sessions', :action => 'new'  
  map.logout 'logout', :controller => 'user_sessions', :action => 'destroy'  
  map.resources :user_sessions
We can also modify our application.rhtml file to add the link for login
<%= link_to "Register", new_user_path %> | <%= link_to "Log in", login_path %>
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:
<% 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 %>
And also add the following code in the app/controllers/application_controller.rb
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 %>


Thats it. We are set to go with our application with this wonderfull gem/plugin for the user authentication functionality.