Date Formatting and Customizing Devise Posted on March 8th, 2011
This week will focus on formatting the rails app to be more user friendly. If this is your first time to this site, please see the first post on making your owns rails blog.
Before we start with this weeks topics I made some basic CSS and formatting changes that can be seen here. Currently the blog displays dates in RFC format and only shows the authors email. This week you'll use Rails I8ln tools to build custom date formatting. We'll also extend Devise, allowing users to login with a user name.
Custom Date Formatting
There are two main theories to Date Formatting. Building a time_format initializer or adding date formats to your locales file. Since date formats differ between regions it makes sense to place these formats in your locales file. Open up
app/view/posts/index.html.erb and make these changes. In locales file, the format named "default" will be used if no format is specified. In the view file, those are L's that have been added prior to the dates. L is a default rails helper method for localize and will apply the localization for that data in our case a timestamp. You can add as many differing formats as you'd like. You can call these by using the following code
<%= l Time.now, :format => :awesome %></code>
Adding usernames is a breeze with Devise. The first step to is create a migration to add the column.
$rails g migration addUsernameToUser username:string
Open up the generated migration and make these changes then run the migration. Since we plan to allow
users to login using their
username we've made it a unique key, the database will not allow more than 1
User to have the same
username. Now that the column is created, modify the
User model to allow editing and validation of
username. We will also make sure that Devise is validating data in the forms. You can see the changes here, user.rb Now that our model and database are set to handle usernames, we have to make sure our views can handle them. To do this we need to extend the default Devise views. Run the following commands and then edit the files as seen here.
$ rails generate devise:views For more information about this as well as how to let user recover their passwords using username or email please see the Devise wiki. Now that we can edit, login and register with usernames, lets display them on our page. Edit post show and post index templates as seen here. Check in next week were we will add comments to the posts.