StaunchRobots dev blog

adventures in programming

Up and Running With AngularJS & Rails

Lately, we at StaunchRobots have started working with AngularJS; a new and increasingly popular Javascript Framework. The purpose of this post is not to describe the great things AngularJS provides you but to outline what we have found to be the best way to start to develop with AngularJS and Rails.

AngularJS is a client-side framework and therefore talks to backend services such as a JSON API. The backend can be programmed with whatever you prefer on the server-side such as Node, Rails or Django.

For the development of the AngularJS app we use Yeoman. Yeoman is a collection of tools that improves and speeds up your development workflow. You can find instructions on how to install Yeoman on their website.

So enough talk, let’s get this thing rolling.

  1. Create the Rails & Angular App
1
2
rails new angular_rails
cd angular_rails

Create the AngularJS app within the root directory of the rails project. To do this you will need to install the angular generators that ship with Yo, one of the tools found within Yeoman.

1
2
3
mkdir angular_client && cd $_
npm install -g generator-angular  (in case you have not installed them)
yo angular client

The last command creates a project skeleton for the AngularJS client app and installs the necessary node packages. For a full list of yo angular generators have a look here.

From now on you should have two terminal windows open. Once parked in the rails root directory from where you run rails specific tasks (rake db:create, rails server, etc.) and the other within the ‘client’ directory inside the rails root directory from where you run AngularJS specific tasks.

Now, while developing the app you will have two servers running. The rails server which provides the JSON API and the development server for your AngularJS client started via the command ‘grunt server’. In order to proxy requests made from the angular app to the rails server you will need to modify the Gruntfile.

  1. Modify the Gruntfile rails_root_path/client/Gruntfile

First, add the following line to the Gruntfile:

1
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;

And specify your proxy setting:

1
2
3
4
5
6
7
proxies: [{
  context: '/api/v1',
  host: 'localhost',
  port: 3000,
  https: false,
  changeOrigin: false
}]

Then, configure the folder to which the ‘grunt build’ command will copy and compile the angular client app just before deployment. Currently we put the angular client inside the ‘public’ folder within the rails root directory and have it served as a static files.

1
2
3
4
var yeomanConfig = {
  app: 'app',
  dist: '../public'
};

You can see a complete gist of a Gruntfile here:

https://gist.github.com/soeffing/6434784/

Finally, run the following command which will install the necessary node package to proxy requests from the angular client to the rails backend.

1
npm install grunt-connect-proxy --save-dev
  1. Getting around CORS issues

Now fire up the two servers (rails server & grunt server). When you try to communicate with the rails API via the http or ngResource services provided by AngularJS you will run into CORS issues. This occurs because the two servers run on different domains (localhost:3000 (rails) & localhost:9000 (angular)). In order to allow CORS add the following code to your application_controller.rb file:

1
2
3
4
5
6
7
8
before_filter :cors_set_access_control_headers

def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'# need to be changed once it goes to production 'http://localhost:8080'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Headers'] = '*, X-Requested-With, X-Prototype-Version, X-CSRF-Token, Content-Type'
  headers['Access-Control-Max-Age'] = "1728000"
end

Now you are clear to develop with AngularJS and Rails. Before deployment you have to run the ‘grunt build’ command within the ‘client’ directory which will compile and copy the angular client app into the public folder of the Rails project.

Expect more AngularJS related posts to come.

Happy coding!

Keeping Your Project Healthy

Whether you are running consultant company or startup or maybe just playing with some code. It’s easy to get caught in the flow of development. With pressure to release features on time, it is increasingly common to accrue technical debt.

Once in a while, it’s very important to step aside of actual development and make a good cleanup, clearing your technical debt, and ensuring a quality maintainable project.

Why care about maintainability?

  • new developers can pick up project very easily and be productive from day 1
  • if you leave project for some time it will be easy to get back.
  • reduce the amount of bugs, and time spent having to fix bugs by clearing up convoluted, time pressured solutions.

I always find myself to do this kind of cleaning up when I join a new project. I have decided to make a list of the things that I find myself doing routinely when joining a new project, this is a sort of checklist if you will.

rails-footnotes

If you write Rails applications on the daily basis, you should know this plugin by Jose Valim. What it do, is displaying all kind of interesting information that happen in the cycle of request. Sessions, request parameters, cookies, filter chain, routes, queries.

There is text editor integration with MacVim, Textmate and SublimeText2. You can jump to particular place in code from footnotes. Also it replaces error page with proper links to files.

https://github.com/josevalim/rails-footnotes

Also take a look at more light alternative: http://miniprofiler.com/

Bullet

The Bullet gem is designed to help you increase your application’s performance by reducing the number of queries it makes. It will watch your queries while you develop your application and notify you when you should add eager loading (N+1 queries), when you’re using eager loading that isn’t necessary and when you should use counter cache.

https://github.com/flyerhzm/bullet

Remove trailing spaces

Seriously, remove them right now! Trailing spaces is a minor detail but it adds a level of noise to git logs in development process. It is very annoying!

Trailing noise

To clean up whitespaces in all files in project you can use following command

1
find . -not \( -name .svn -prune -o -name .git -prune \) -type f -print0 | xargs -0 file -In | grep -v binary | cut -d ":" -f1 | xargs -0 sed -i '' -E "s/[[:space:]]*$//"

Script goes through all files except binary and source control files and removes trailing whitespaces.

Setup text editor to remove trailing spaces before saving file

  • sublime

    Recently popular Sublime Text 2 have this functionality built in by default. You just need to add following string to configuration file:

1
  "trim_trailing_white_space_on_save": true

Keep your seeds fresh!

Seeds are very important, whether it’s demo(developer) data or actual production seed. When updating models associations or structure do not forget to reflect this changes in seeds.rb file. On one of our projects I spend TENS of hours working on seed script and sample data, so we can deploy fully working staging application in no time. Any time that customer wants to check a progress. This tends to be an area that get habitually neglected, and makes proper testing, and staging impossible.

Another antipattern that I usually see is folks keeping seed data in migrations. Seriously why you want to dig to migration every time you forget password for admin user?

active_admin example

Extract modules

Go through all the models and check if you can extract some code from models to general utility modules. This will(hopefully!) not break anything inside but make code more readable. Also consider to going even further - apply SRP(Single Responsibility Principle) and compose classes that do only one thing, but do it good.

Make a decent README file

There is 3 types of readme files for rails projects. Most popular is almost empty readme file with project name and short description. Next by popularity is file starting with line “== Welcome to Rails”. Rare beast is readme file that actually reflects the project, shows you installation instructions, usage patterns, goes through custom rake tasks that used to run project and guide to run tests!

Check out Readme Driven Development

Do not forget about /doc folder

This folder can be very good to keep your project documentation. Of course we all know about github wiki pages or basecamp or any other knowledge base of choice. But do you really want to be dependent of external service to keep your documentation?

With just a few keystrokes in your editor you can have access to all documentation related to project. Credentials, setting up development machine, deployment, testing, tips, technical debts, just random ideas, list can go forever.

But wait, it’s not the best thing yet. The best thing is you can track changes in documentation just going through commits! Why use two places for tracking news in the code instead of one?(SCM)

1
2
3
4
5
6
  git rm -r --cached doc/
  git commit -m 'Removed doc folder from repo'
  rm -rf doc/

  git submodule add git@github.com:user/project.wiki.git doc
  git commit -m 'Initialize wiki doc repository'

Before running that script you need to tell github to create wiki repository by hitting url: http://github.com/user/repo/wiki/_access Your doc/ folder will be separate submodule inside your repo. You can keep a good track of what is happening inside doc/ directory.

Pro Tip

RVMRCFY!

Create and check in in to repository .rvmrc file with specific version of ruby that you will be running. This will keep everyone on the same page while development process. I was in situations when my version of ruby as miserably failing on tests while it was working for everyone else, this is easilly avoidable!

If you using zsh, here is function that will help you to easily create .rvmrc file for project

Pro Tip

Newrelic rpm

Setup free account to monitor your servers. Newrelic is sending emails when your CPU or memory is over threshold. Also by default you can browse page response time and find controllers that spend most of resources.

NewRelic

Live metrics

Instrumental App makes it easy to see what’s happening in your application right now. Collecting live information about performance of application can get your eyes open on a lot of things. With just few changes you can save hundreds of dollars on hardware.

Check out https://instrumentalapp.com

Code Climate - collect metrics

The best way to reflect on code is to collect various code metrics.

Check out https://codeclimate.com/

Use capistrano to deploy(unless you using heroku)

Use automated deployment with no excuse! Either heroku or capistrano or even rsync

gist

Wrapping up

This is list of most common things in every project, hope this will help you to make your project more maintainable. <3 <3 <3

TomDoc Package for SublimeText2

TomDoc package for SublimeText2

TomDoc - is a code documentation specification that helps you write precise documentation that is nice to read in plain text, yet structured enough to be automatically extracted and processed by a machine.

SublimeText2 - is very powerfull text editor that are taking over TextMate right now.

So to promote writing of documentation in your company, one approach is to build tools around helping programmers write it!

Motivation for this plugin was to have fully functional TomDoc plugin.

You can find source code https://github.com/shell/sublime-tomdoc

Installation

Right now package is not accepted to package manager source, so only way to install it is to go SublimeText2 packages directory and do:

1
git clone git@github.com:shell/sublime-tomdoc.git

Usage

Pressing ctrl+enter on the previous line of method definition

1
2
def hello a, b
end

results to

1
2
3
4
5
6
7
8
9
# Public: Duplicate some text an arbitrary number of times.
#
# a -
# b -
#
# Returns the duplicated String.
def hello a, b

end

Works respectfully for all other supported constructions

Other usage way is to type ‘tom’ and hit TAB to generate default TomDoc skeleton text.

Plugin supports following constructions for TomDoc:

  • Method Documentation
  • Initialize method Documentation
  • Class/Module Documentation
  • Constants Documentation
  • Attributes

What do you think?

Shoot us email if you have some problems with this plugin or want specific features

Switching to Zsh and Why You Should Do It Now

Switching to zsh and why you should do it now

If you working with ruby or rails, there is big chance that you spending lots of time in console. Yeah you probably using already this wonderful project that helps you everyday called iTerm2. But why don’t make your work even more comfortable?!

zsh - is a shell designed for interactive use, although it is also a powerful scripting language. Many of the useful features of bash, ksh, and tcsh were incorporated into zsh; many original features were added

oh-my-zsh! - A community-driven framework for managing your zsh configuration. Includes 40+ optional plugins (rails, git, OSX, hub, capistrano, brew, ant, macports, etc), over 80 terminal themes to spice up your morning, and an auto-update tool so that makes it easy to keep up with the latest updates from the community

There is no reason why not to try it, automatic script will install everything for you. If you decide to stick up with good old configured bash, just run uninstallation script.

Installation

Installation is deadly easy:

via curl

1
  curl -L https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh | sh

via wget

1
  wget --no-check-certificate https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | sh

If you have some troubles - manual installation is available. After installation open up new console window and say “OH-MY-ZSH!”

All configuration is done via .zshrc file.

Features

zsh comes with a bunch of nifty functionality built in and oh-my-zsh comes with handful of interesting plugins.

I will not explain how to enable them here, but roughly will go through best. You can find plugins in ~/.oh-my-zsh/plugins folder.

bundler

Plugin adds nifty shortcuts like:

  • bi for ‘bundle install’
  • be for ‘bundle exec’
  • bu for ‘bundle update’

Also it wrapps all regular commands that can require ‘bundle exec’ before them and add it for you. Now you will never need to run command twice, just because bundle wasn’t setted up properly.

cloudapp by Zach Holman

CloudApp allows you to share images, links, music, videos and files. Usually you just drop files to icon and app automatically uploads them to cloud and drops short link into your clipboard. It automatically uploads screenshots from your desktop.

Plugin allows you to upload a file from the command line to CloudApp.

git

Adds lots of aliases to type less while using git. Something that you probably already setted up is: ga(git add), gb(git branch), gc(git commit).

One of my favorites are:

  • ggpull - pulls current branch from server. Like ‘git pull’ but with current branch name
  • ggpush - same as previous but for push
  • ggpnp - doing pull and then push for current branch.

github!

Plugin adds nifty commands to manage your github repositories:

  • empty_gh - creates new repo from scratch. Adds README file and pushes to your account
  • new_gh - Used for directory not setted up for git yet. creates .gitignore and README files and pushes to github
  • exist_gh - use this one when github repo is setted up already you just want to add remote and push updates from here

osx

Some commands to rule your system:

  • tab() - opens up new tab in your terminal of choise(Terminal.app or iTerm2)
  • pfs() - returns path for selected item in finder
  • cdf() - cd’s to selected item in finder
  • quick-look() - opens up file with quick-look

pow

Pow is a zero-config Rack server for Mac OS X.

So this plugin adds few commands to rule that doomsday device:

  • kapow - a command that will restart an app
  • powit - makes symlink from current directory so it will be served by pow
  • kaput - view the standard out (puts) from any pow app

rails and rails3

Some aliases:

  • rc - rails console
  • rg - rails generate
  • rgm - rails generate migration
  • rs - rails server
  • rsd - rails server –debug
  • mig=’rake db:migrate’
  • roll=’rake db:rollback’

textmate

Some aliasses:

  • et - ‘mate .’
  • mr - Edit Ruby app in TextMate

vi-mode

One of my favorite plugins. Brings power of vim move/edit commands in console

But wait, it’s not all! Most of plugins for particular tools(git, github, bundler, brew…) adds autocompletion for this commands.

More information

Ryan Bates have wonderful screencast about oh-my-zsh http://railscasts.com/episodes/308-oh-my-zsh

Gemifying Your App for Fun and Profit

So you want to make a gem? Here’s how:

First, make something you’d like to gemify

I’m not going to help you with this part. For now let’s just assume that you have an application that you’d like to share with the world in an easy way. If you’re working in the ruby world, that’s through creating a gem.

Wait, tell me again why we’re doing this…

Let’s use my specific situation to illustrate. We’re making a command line application that we share with the subscribers of our service so that if they are versed in *nix systems they can automate the use of our service. Before I gemified the command line application, here’s what a user had to do:

  1. Clone the files off github
  2. cd into the new directory
  3. bundle install
  4. set up user credentials in a yaml file
  5. type “bin/cloudalign”

In addition to all of these steps, step 5 will ONLY work in one directory. Let me show you the steps after gemifying:

  1. gem install cloudalign-cli
  2. set up user credentials in a yaml file
  3. type “cloudalign”

Not only are there fewer steps, but two of the three steps that are left require less technical know-how (and we’re working on making step 2 easier as well, but simply gemifying doesn’t help that).

If you’re convinced, let’s go. If you’re not, then go ahead and distribute your app the old-fashioned way and come back when you’re wiser ;)

First, make a gemspec

In the main directory, create a file called YOUR_APP_NAME.gemspec. In this file, you’ll put something like this:

Gem::Specification.new do |s|
  s.name = 'cloudalign-cli'
  s.version = '0.1.1'
  s.platform = Gem::Platform::RUBY
  s.authors = ['Jonathan McCaffrey', 'Jeffrey Biles']
  s.summary = %q{Access cloudalign from your command line}
  s.description = %q{Cloudalign brings the power of the cloud straight to your lab}
  s.rubyforge_project = "cloudalign-cli"
  s.files = Dir.glob("{bin,lib}/**/*") + %w(README.md)
  s.executables = ["cloudalign"]
  s.homepage = 'http://rubygems.org/gems/cloudalign-cli'

  s.add_dependency("thor")
  s.add_dependency("rest-client")
  s.add_dependency("formatador")
  s.add_dependency("rspec")
end

Most of these fields are self-explanatory. Name, authors, summary are exactly what they sound like. add_dependency is just a list of the other gems required (what you have in your gemfile). The version number is for semantic versioning (or, if you prefer, terrible non-semantic versioning).

The ones you must pay attention to are ‘files’ and ‘executables’. The ‘files’ entry was stolen from (if memory serves correctly) a blog post by yehuda katz. You can copy it verbatim, though you may want to include a few more extraneous files aside from the readme. In the ‘executables’ entry, you put the main executable file of your app, usually found in the ‘bin’ folder.

Second, bundle it all up

Like the previous steps, this one is also easy. In the command line, while in the main directory of your app, type gem build YOUR_GEMSPEC_FILE. You’ll get a message saying that a gem has been created. This will be a file named GEM_NAME-GEM_VERSION.gem.

Test this by typing gem install GEM_NAME-GEM_VERSION.gem (installing using the gem that was just created). This installs it in your system, as a gem. Finally, test it by running it just like you expect your users to. In this case, I would type cloudalign project list, and sure enough it works as expected (return a list of the projects that the user is involved in).

Great! You’ve got a gem! Now to distribute it.

Third, push to rubygems

Rubygems is the standard way that developers publish their open-source gems. If you wish to keep your code closed-source, there are ways to do that, but hosting your gems on rubygems is the general practice, and extremely simple to boot.

Here are the steps

  1. sign up for a rubygems account
  2. download some of their tools by typing curl -u RUBYGEMS_USERNAME https://rubygems.org/api/v1/api_key.yaml > ~/.gem/credentials
  3. type gem push GEM_NAME-GEM_VERSION.gem

Fourth, test on another project

In another project, type gem install GEM_NAME. Test to see if it works as intended.

Fifth, fun

Your code is now WAY easier and more fun for others to use.

Sixth, profit

(unless you’re twitter)

Sinatra Template

Recently I found myself doing a couple of very simple services for my cliens with Sinatra. Just some basic authentication, active_record and mysql2 database, few forms, rails view helpers. There is a lot of guides and tutorials around internet. But it seems that there is no good Sinatra template with testing coverate, basic files structure, etc.

So I made one! Sinatra Template

Features

* HTTP basic authentication
* ActiveRecord orm
* Sqlite3 for development, Mysql2 for production
* 2 very basic but associated models
* HAML, blueprint, jquery
* User and Admin interfaces
* Scroller with products
* Full rake tasks for db management(hacked sinatra-activerecord gem)
* Testing suite out of the box(RSpec)
* Some essential Rails helpers
* Ready for deploy with passenger(config/setup_load_paths.rb)

Some prefer to extract controllers, models and helpers in corresponding folders and split them over files. It is a matter of taste. If you have that much code, consider using Rails instead.

Enjoy