Tracking views in Rails

Tracking views in Rails is very simple!

Some weeks ago I was asked to implement a feature that will be tracking the users’ profile views. As I come from a background of Java and PHP I was thinking of ways to efficiently implement something like that and prevent any database performance issues in future.

I decided to make it as simple as possible and then improve from there. Just after some minutes, and with some Ruby magic, I had it working!

Tracking views in Rails is really simple. Feel free to checkout my implementation on Github.

You can also use this for tracking views/impressions for Articles or Posts.

Ready to Release a Rails App?

“So, you are ready to release a Rails app? Awesome!”

When you are ready to release a Rails app (or your team’s app), there will be many tasks you need to handle and plan for. The World Wide Web is a “hostile” environment. As a result, when you release your Rails App you will face a load of different issues such as bugs, vulnerabilities, security flaws, performance issues, errors, warnings, lack of data analysis and monitoring and lastly difficulties to debug and respond to all these!

Gladly, nowadays, there are solutions out there that can help you respond and give you an edge at tackling all these issues.

First of all, I suggest that, before releasing your app you should get your Application’s code reviewed. You can either hire an experienced Senior Rails engineer (or a team) to go through your Rails App’s code or use a cheap and quick automated tool like Pullreview.

NewRelic is an excellent tool for Application Performance Management & Monitoring. It is relatively complex in comparison to other tools but it is a professional full scale platform. I personally use it to monitor my server’s CPU, memory stats, database and other website related stats such as page load time, errors, etc). In that way I can respond to potential performance issues or bottlenecks.

As we use Ruby on Rails, gemnasium is an excellent choice for monitoring vulnerabilities of our App’s gems and their dependencies.

Sentry and Airbrake are excellent tools that keep track of exceptions generated on your website by users. In that way you will be able to spot bugs and debug faster and easier. Also, it will be awful and time consuming to try searching your logs in order to find errors.

And lastly, you should keep track of the website users’ behaviour and features’ utilisation. Google Analytics with custom events would be sufficient but I also recommend that you check out

And now… You are ready to release a Rails App! 🙂

Gemnasium Review

“Gemnasium; an automated tool for tracking your dependencies.”

Our team is ready to deploy our Rails application. When a Rails application reaches this stage there are security concerns that should be addressed. Rails apps use gems as are sometimes required and sometimes beneficial for saving time and having a high quality implementation. However all these gems are consisted by dependencies which can introduce vulnerabilities. It is difficult to track these vulnerabilities as are many in number and a time consuming process.

Gemnasium (website) comes in and gives an efficient solution for this task. By subscribing to this service, your Rails application dependencies are tracked. When a new vulnerability is found you are notified via an email.

We have been using Gemnasium lately and had a very pleasant experience with it. In two different cases we received alerts on our email. The friendly interface makes it easy to identify which gem needs to be updated. Then, its just a matter of changing your gem’s version in your Gemfile.

The alerts are in real-time and you can also add several members on your Gemnasium account. As a result, your whole team can receive the vulnerability alerts and fix the issues immediately.

Rails 4 Devise Username

“Some users prefer username authentication but some email – Rails 4 Devise Username”

You desire to create the ability for your user’s to login with either their Username or Email. Luckily this task is really simple in Rails 4 Devise Username.

First of all make sure that you have the “username” attribute in your Users database table. Then in your view – where the user signs in – (app/views/devise/sessions/new.html.erb) replace the email field with:

<%= f.label "Username or Email" %>
<%= f.text_field :login %><br>

The parameter “login” will be used to later describe either the user’s email or username. In the user.rb model you need to make the following additions:

attr_accessor :login

def login=(login)
  @login = login

def login
  @login || self.username ||

def self.find_first_by_auth_conditions(warden_conditions)
  conditions = warden_conditions.dup
  if login = conditions.delete(:login)
    where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first

With these changes we assign the login parameter to the desired value and determine if the login value used was an email or a username.

As we use Devise, there is a need to permit the login parameter on Devise’s end. Also don’t forget to change Devise’s default authentication_keys from email to login.

In the app/controllers/application_controller.rb under the def update_sanitized_params method we should add login for sign up:

devise_parameter_sanitizer.for(:sign_in) {|u| u.permit(:login, :username, :email, :password, :remember_me)}

and in config/initializers/devise.rb, we should change the “config.authentication_keys = [ :email ]” to “config.authentication_keys = [ :login ]”

That’s all! If you have any difficulties or feedback feel free to contact me or leave a comment below.

Setting up Ruby on Rails Development Environment

“When it comes to Web Development via Ruby on Rails, I prefer working with the Mac OS X.”

OS X makes it so easy for setting up Ruby on Rails development environment; but I still observe other junior developers having troubles with setting it up.

Seven simple steps!

1. First of all, Mac OS X provides Xcode and Xcode Command Line Tools which are development tools. You can download them from the Apple Developer site.
2. Then, install homebrew: ruby -e “$(curl -fsSL“. After the installation, run “brew doctor” to make sure homebrew works fine. If not, follow the instructions of the message that appears.
3. Install GCC 4.2 by inputting “brew install apple-gcc42” & “sudo ln -s /usr/local/bin/gcc-4.2 /usr/bin/gcc-4.2“.
4. Install RVM with “curl -L | bash -s stable –autolibs=enabled
5. Install Ruby 2.0.0: “rvm install 2.0.0 –default” (or any other version: “rvm install “version”).
6. Lastly, install Rails(and the bundler): “gem install rails bundler –no-ri –no-rdoc
7. Tip: If have any errors about missing libraries then just search on google about the libraries associated with the error and then execute: “brew install [library-name]

1. Will you be uploading your code to Github? Install git with: “brew install git
2. Will you be working with SQLite3? Install it with: “brew install sqlite3
3. Will you be working with MySQL? Install it with: “brew install mysql
4. Will you be working with PostgreSQL? Install it with: “brew install postgresql

Working with Timestamps

“Working with Timestamps is a usual task in Rails.”

Many times you find yourself in need of a friendly date and time format. Luckily, Rails’ Helper methods provide many different ways to make this possible. A timestamp in Rails is shown like: “2014-01-17 23:36:54 +0000”. So what if we want to present the time that a blog post was created in a friendly format? For example: “This post was created on the 17th Jan, 2014 at 23:36”?

For grabbing the year, month and day we can call “post.created_at.year”, “post.created_at.month” and “post.created_at.mday” respectively. For grabbing the time we can call “post.created_at.strftime((“%H:%M”)”.

Note that all these variables will return numbers. However, in our example we need our month to be the abbreviation of January. For doing so, we just use the I18n ( Rails Internationalization API ) with a code like: “I18n.t(“date.abbr_month_names”)[post.created_at.month]”.

So, working with timestamps in order to show “This post was created on the 17 of Jan, 2014 at 23:36”, we will use this in our view:

This post was created on the <%= post.created_at.mday %> of <%= I18n.t("date.abbr_month_names")[post.created_at.month] %>, <%= post.created_at.year %> at post.created_at.strftime(("%H:%M")

Another great way to present time in a friendly format is by using “time_ago_in_words(post.created_at)” which will render a format like: 3 days ago or 15 minutes ago.

has_many :through association

Scenario: Users should be able to select their kills which can be later shown on their profile’s account.

There are two ways to do so. The has_many_and_belongs_to and the has_many :trough associations. In the following example I will use the second one so we can see the whole structure of creating such association.

There are three models concerned which are User, Skill and User_Skill.

The User model should be similar to this:

  has_many :user_skills
  has_many :skills, through: :user_skills

The Skill model should be similar to this:

  has_many :user_skills
  has_many :users, through: :user_skills

And the User_Skill should be similar to this:

  belongs_to :user
  belongs_to :skill

In terms of storing data in the database, there is a need of a user_skills table that has user_id (integer) and skill_id (integer) columns. In that way the user’s and skill’s id will be stored for retrieving them later in the view.

In the controller a method will be used to store the user skills:

def skills_modif
  skill_ids = []
  skill_ids << params[:user_skills]
  current_user.skill_ids = skill_ids

This method creates an array called skill_ids, injects the skills that the user selected with the “:user_skills” symbol and then sets current_user.skills to these new values. After that the user is saved.

So the last step is to create a from in the view in which the user can select skills. A suggestion would be to use a form select attribute with options_for_select property that will grab all the Skills from the skills table in the database. In addition, by using the options multiple and width (e.g. {:width => 5, :multiple => true }) the user will be able to select multiple skills.

Rails 4 Simple Search Form

“Some features need different implementation than in Rails 3. Here is a proper Rails 4 Simple Search Form”

I have been working on a new project for a while now. I am using Rails 4 and I observed that some features need different implementation than in Rails 3. For example, let’s create a Rails 4 Simple Search Form for Users. You will need to work with all MVC elements.

In the User’s Model we will create a method for searching the database and returning an exact match of a query.

  where("email like ?", "%#{query}%") 

In the Users Controller we need to trigger the search function in our model.

def index
  if params[:search]
    @users =[:search]).order("created_at DESC")
    @users = User.all.order('created_at DESC')

And lastly, the View will use form_tag with a GET HTTP method.

<%= form_tag(users_path, :method => "get", id: "search-form") do %>
  <%= text_field_tag :search, params[:search], placeholder: "Search Users" %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

Keep in mind that we use “:name => nil” so that the “commit=Search” is not appended in the URL address.

Rails Messaging System from Scratch

“A great implementation to play around.”

Yesterday I implemented a Rails Messaging System from scratch. It was just a simple system so that Admins and Clients could communicate with each other. Briefly, the implementations were:

  • Admins and Clients can send and receive messages.
  • Only Admins characterised as ‘Super Admins’ can use the messaging system.
  • Admins receive a notification if the user read the message they sent.
  • Basic front-end design using Bootstrap and custom CSS styling.
  • Admins can delete messages.
  • Both user types can see sent messages.
  • Essential Validations.
  • Refactoring of controller and use of a helper file.
  • Security – Unauthorised for all users that cannot use feature. Also, users can see messages that they sent or received.

It took me a whole day to implement this Rails Messaging System but, it was fairly easy. I suggest this feature to new Rails developer for practise. It is a great implementation to play around and take your knowledge a step forward.

I created this feature for an organisation and as a result I cannot share its source code. However, I created a new project and applied the feature on github. Keep in mind that front-end styling was not the focus.

Verification Tests or Test Driven Development?

“Test Driven Development makes you write solid code.”

Testing is an essential part in development. My 9FUN application has no tests so far. When i began writing this app, I was in rush to implement its features rather than ensuring its functionality. I now understand that this action was wrong. Testing is essential. If you expect users to use your application, then testing must take place. A good lesson taught though. I decided to halt on creating new functionalities and test all of my features.

A good approach from now on would be to test each feature after its completion. In order to get a little deeper into testing I studied the Everyday Rails Testing with RSpec book by Aaron Summer. I found this book simple and interesting! I highly recommend it to anyone new in testing. Also, it can be used as reference when you want to look up something.

After finishing the book, I felt that, as I am familiar with Test Driven Development, I should be following Test Driven Development rather than making a verification tests after a feature’s completion. I am more drawn into Test Driven Development as its logic is really simple and you only need to write the necessary code each time. This makes your code look better without any “code smell”. In addition, by following Test Driven Development you write solid code and ensure that any new modifications or new code will not break your application. After a successful test you can go on and work on refactoring and front-end styling.