ParsaLabs | Blog

A publication about the web and more.

Namespaced Routes and Restful Controllers in Rails

| Comments

Often times in web projects it’s required that we provide distinct interface(s) to different types of users. In my opinion, a good practice in this case is to keep the business models unique, but separate controllers and views for different roles. Fortunately rails supports this out of the box with a feature called namespaced routes. If you take a look at the last commented block in your routes.rb file, you will find it hidden there. In this post, I will try to explain how to use it. So, let’s say you have a blogging application with 2 sets of users (normal, and admin) accessing the same resource (post model) but in different ways.

Controller

To generate public controller for public users:

1
rails g controller posts

For admins:

1
rails g controller admin/posts

The second generator will create controllers/admin/posts_controller.rb, and a folder for the views in views/admin/posts.

Routes

For public users:

1
resources :posts, only: [:index, :show]

And a namespaced route for the admins:

1
2
3
namespace :admin do
  resources :posts
end

As a result, you will get 2 sets of distinct routes for public and admin access. Check them out by running rake routes in terminal.

Get the form_for right (for admin)

1
2
3
<%= form_for([:admin, @post]) do |f| %>
  # your usual form helper go here..
<% end %>

jQuery UI and Rails

| Comments

It seems like jQuery UI library has been removed from the latest versions of Rails. But no worries, it can be easily added back to your app through the jquery-ui-rails gem (in 3 quick steps):

(1) Add to your Gemfile:

1
gem 'jquery-ui-rails'

and run bundle install.

(2) Add the following line to your application.js file:

1
//= require jquery.ui.all

(3) And finally, add the following line to your application.css file:

1
*= require jquery.ui.all

And you are done!

Note:

If loading the entire library is an overhead for you, and you prefer to selectively load individual components you need, you can do so like this:

application.js :

1
//= require jquery.ui.datepicker

application.css :

1
2
3
/*
 *= require jquery.ui.datepicker
 */

to, for example, load the date picker module.

Announcing a New Product by ParsaLabs: ResumeMadeEasy.com

| Comments

I am excited to announce the alpha release of ResumeMadeEasy.com, whose purpose is to solve common problems faced when dealing with resumes. It was built to address my own need to be able to create and/or update my resume with ease, and faster. Some of the problems I had (before using ResumeMadeEasy.com) were:

  • I always had a hard time locating the latest or a specific version of my resume. They were scattered across email, dropbox, google drive accounts. Some were even stored offline on my flash drives, etc. It was all a total mess. In many occasions, I would have to abort the hunting and resort to modifying an older version of my resume, because it was the only one I could find at the time. Fortunately now, all of my resumes are conveniently stored in 1 central location, so I don’t have that problem anymore.

  • Styling and designing resume layout used to be an absolute pain in the butt. I usually would have to go through many iterations to get it right (sort of!) and that was a waste of time. But now, using ResumeMadeEasy.com, I just enter my data/information through web forms and let the site worry about styling it.

  • One of the best formats to have your resume in, is PDF. It’s universal, it’s standard, it’s viewed the same way everywhere. But good luck converting to it from another format! ResumeMadeEasy.com makes it a breeze. I can’t begin to appreciate how relieved I am now that I don’t have to worry about conversion to PDF. It’s one of my favourite features on ResumeMadeEasy.com.

  • Another feature I absolutely adore is the copy/duplicate resume capability. Often times, when applying for a different type of job (with different requirements) I find myself needing to tweak my “standard” resume slightly, and add sections and/or rearrange existing items a little bit, to highlight the relevant skills required for the position. But I have realised, time and again, that almost 80% of the items are the same. It would be great if I could sort of duplicate one of my existing resumes, and use it as a starting point to make necessary changes. ResumeMadeEasy.com enables you to do just that, by providing a “copy” button for every resume you build. It’s a small feature, but with huge impact.

  • And finally, ResumeMadeEasy.com is a free service. Even as we add new resume templates/designs, new features and enhancements, you don’t need to pay a dime.

I created this utility with care and passion, and decided to make it available for everyone to benefit from. I hope you find it useful and enjoy using it, as much as I do.

Finally, I value your feedback and suggestions greatly. If you have a feature in mind (that you think should be added to ResumeMadeEasy.com), or face a problem while using the service, or just have a question, please feel free to let me know. You can contact me either through the feedback form on the website, or by directly sending me email at pouya@parsalabs.com. Be sure that all of your messages will be read by me. :)

Sincerely, Pouya

Textmate 2 Tips

| Comments

I use Textmate for all of my code editing. Learning how to use it effectively, is key to more productivity. Fortunately, today I found 2 great blog posts by Hilton Lipschitz on exactly the same topic, and with his permission, I am sharing them here in this post:

Enjoy, and don’t hesitate to add your own tips in the comments section.

Kill PIDs on a Certain Port in Mac

| Comments

I use Phusion Passenger (in conjunction with foreman) for some of my projects, and one problem I face is that even after I stop the standalone server by pressing Ctrl-C, passenger continues to occupy port 5000. So when I do foreman start to run the server again, I get an error saying port 5000 is already in use. However, this issue fades away when I manually start Phusion Passenger’s standalone server using the following command in terminal:

1
bundle exec passenger start -p $PORT --max-pool-size 3

as opposed to the normal foreman start. But anyways, this was a chance to learn (on Mac OS) how to find processes that are using certain ports, and kill them. Here’s the script that works for me:

1
lsof -P | grep ':5000' | awk '{print $2}' | xargs kill -9

Cheers

PDF Generation With WKHTMLTOPDF

| Comments

Recently, I’ve had the need to be able to generate PDF files from HTML content. Programmatically generating PDF used to be a hard problem in software development. But there are some utilities that has made this task much easier to accomplish. The most stable I have found so far is a shell utility called wkhtmltopdf. Since I primarily develop apps with Ruby on Rails, there are also a few awesome plugins and gems available that help integrate wkhtmltopdf functionalities into any rails app through ruby APIs. For example: PDFKit, Wicked_pdf, etc. However, you still need to manually install the shell utility yourself, manually. And that’s the tricky part (especially, when you develop and deploy on different platforms). But I managed to finally figure it out, and thought I’d share my recipe in this blog post. Here it goes:

Installing wkhtmltopdf on Mac OS X (for my development)

While many might argue that brew install wkhtmltopdf is the best option (and using homebrew package manager is generally the best option), I had a few issues with it. First of all, it seemed like homebrew installed an older version of wkhtmltopdf binary for me, therefore I was not running the latest binary with all the updates and patches (particularly for QT). And as a result I was faced with many bugs when generating pdf files: for instance, every time my rails app called wkhtmltopdf, an icon would appear in Dock and the application would halt, and I had to manually click on it for execution to resume. Also, I experienced many instances of split text bug in the generated pdf. and more..

So, I decided to install the official Mac OS release:

  • I downloaded the .dmg
  • double-clicked to open it
  • dragged it to Applications folder

and did the following in the terminal:

1
2
cd /usr/local/bin
ln -s /Applications/wkhtmltopdf.app/Contents/MacOS/wkhtmltopdf wkhtmltopdf

Your wkhtmltopdf shell utility should now be installed properly. Test it by restarting the terminal and typing: wkhtmltopdf --help.

Installing wkhtmltopdf on Linux

This is pretty trivial. Just download a linux version of the static binary (for example this one) and place it in a path that’s accessible by your rails app.

Pointing to wkhtmltopdf (in PDFKit config)

Last step is to point to the correct binary for PDFKit to work on both development and production server. Here’s my config:

1
2
3
4
5
6
7
8
9
PDFKit.configure do |config|
  
  if RUBY_PLATFORM.include? "darwin" # My development Mac OSX
    config.wkhtmltopdf = '/usr/local/bin/wkhtmltopdf'
  else
    config.wkhtmltopdf = '/path/to/wkhtmltopdf-static-binary' # customize this for your production app.
  end
  
end

Hope this was useful. :)

Create a Blog With Octopress + Deploy to Heroku

| Comments

As promised in a previous post on sharing, I am going to show you how to create a weblog with Octopress (which is a blogging framework/engine), publish posts and deploy to heroku. So, let’s get to it:

Note: I am assuming that you have gone through my post on setting up Ruby/Rails environment, and that you have installed ruby 1.9.3 (or greater) using rbenv tool. For the purposes of this tutorial, I am going to go with ruby 2.0.0-p353.

Start by cloning the project and installing its dependencies:

1
2
3
4
5
6
git clone git://github.com/imathis/octopress.git myblog
cd myblog
rbenv local 2.0.0-p353
gem install bundler
rbenv rehash
bundle install

We are going to to use Octopress’s default theme for now (but really, you can tweak the html/css and add your own style/templates/etc):

1
bundle exec rake install

Your blog is ready. Of course it has nothing in it yet! But for those impatient among you, run the following commands:

1
2
bundle exec rake generate
bundle exec rake preview

and point your browser to http://localhost:4000 and you should be able to see your blog served up!

Now, let’s add a new post:

1
bundle exec rake new_post

…and when prompted, enter/type your desired title for the post, and hit enter/return. You will see in the output that a new file (with .markdown extension) is created in your source/_posts directory. File name is a combination of date and title you just typed, which means your file name will differ from mine. but it should look something like this: 2013-12-17-my-first-blog-post.markdown.

Open this file in your favourite editor and append some text to the bottom of it. Finally, save the file.

Now, do:

1
2
bundle exec rake generate
bundle exec rake preview

and visit http://localhost:4000 in your browser again. You will see your new blog post there. Yaaay!

Heroku Deployment

First, add:

1
gem 'unicorn'

..to your Gemfile, and run bundle install to install it.

Next, create a Procfile at the root directory of your blog application like so:

1
touch Procfile

Open this file with an editor and add the following content to it:

1
web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb

Now, we are going to create a directory named config at the root directory of your application and add the unicorn.rb file to it, like so:

1
2
mkdir config
touch config/unicorn.rb

Again, open this file with an editor and add the content below to it:

1
2
3
worker_processes 4
timeout 30
preload_app true

Lastly, open .gitignore file and delete the line that says public. This is so that we can commit the public directory to git and push it up to heroku (public is where the generated static html content lives).

Save your work in git:

1
2
git add .
git commit -m 'ready to publish to heroku'

Assuming you have an account with heroku (and the toolbelt properly installed) go ahead and push everything up to heroku, like so:

1
2
3
heroku create
git push heroku master
heroku open

Enjoy your blog, served up by Heroku! :–)

Customization

As I mentioned before, you can customise your Octopress blog to your heart’s content: by using your own html layouts, changing the existing CSS styles, adding twitter/google analytics accounts, Facebook like button, adding new pages, etc. These are outside of the scope of this blog post. Here are a few pointers to the official documentation:

A Personal Thought

When you get into the habit of writing a blog post after learning something new, not only are you giving others the chance to learn too, but also you are documenting your very own knowledge and thoughts. This way, your blog serves as a personal reference. It has happened to me so many times that I referred back to my own post for instructions on setting up a ruby/rails environment when I reinstalled OS X, and/or bought a new Macbook.

Github

For your reference, you can find the source code of the blog we created together in this post, here in my github account.

On SJR

| Comments

I have always had strong opinion on this topic and recently was thinking of writing up a blog post to not only organise my own thoughts, but also to share with you why I believe using this approach leads to better code, and happier development experience.

Fortunately, David Heinemeier Hansson, the creator of Rails Framework, just wrote an awesome article on this matter on 37signals’ blog.

Read it here: Server-generated JavaScript Responses.

I particularly acknowledge the point David made about “easy-to-follow execution flow”. Using this approach, you follow the same conventional MVC flow, just that instead of spitting out HTML, you return Javascript. In my experience, this results in a much more maintainable code, and is less distracting to the developer (you are not making a major context switch). Whereas, premature usage of client side MVC, means that you end up with an MVC on the backend, and an MVC on the front (therefore, complexity = MVC2). And the more complexity is introduced, the harder it gets to kill bugs, maintain code, etc.

So, embrace this approach, folks! :)

On Sharing, and Why It Matters

| Comments

There are many advantages associated with sharing, but what I want to talk about in this blog post is one aspect which has (in my opinion) contributed significantly to the very success of the rails ecosystem. Since I started working with rails, I’ve noticed that the community is full of nice and caring people who share their knowledge and help others learn. This is achieved in many different ways: from creating fully fledged learning sites like codeschool.com and railscasts.com (from which I have benefitted immensely) to the vast array of awesome, high quality, well-maintained ruby gems made available by community members. Often times, you find Rubyists contributing back to the community (as much as they can) which results in the ecosystem as a whole to be enriched further. Collectively, we have achieved a stack of tools, libraries and resources which are very helpful, and this couldn’t have been made possible if we had not had the virtue of sharing. Rails itself was extracted from DHH’s work on basecamp. He could have kept it to himself and not care to share his work with others, but he was generous enough to do so, and hence we have one of the best frameworks to develop web-based apps with (and in my opinion, a very well designed piece of software that brings much happiness to developers).

More tech companies should open up, too. Now, after talking to a fair number of people in IT, I have realised that unfortunately one of the things preventing some of them from sharing is that they think by making their recipes known, they “risk” giving away important & secret information about their idea, product or whatever it is that they are working on. This, I believe, is a false notion. Take cooking books for example. Chefs who write those books are not worried that someone might steal their secret recipe, open a restaurant next to theirs, and compete with them. That’s just not how it works.

Lastly, another gain of sharing, which I have experienced personally, is the sense of joy that comes with it. It’s very satisfying to see others benefit from your recipes/solutions/methods, etc. So, do give it a try. A good way to start, you ask? I suggest you establish an online presence immediately, through a weblog. Fortunately in the ruby world, there is an awesome blogging engine, called Octopress, that makes this extremely simple. In fact, Octopress is the very engine that powers ParsaLabs weblog. In my next blog post, I am going to walk you through the steps involved in creating a weblog with Octopress and deploying it to heroku. So, stay tuned for that ;–)

Together we can achieve the unimaginable.