– we create awesome web applications

Stop using strftime. Seriously. At least if you are using Rails that is.

Rails, or rather, its I18N dependency, has a much better alternative I18n.l. The great thing about it is that you provide the name/kind of the format that you want separately of the format itself, so that you can, for example, change it completely for the whole application, or for a different locale.

The usage is quite simple. Instead of

Time.now.strftime('%Y-%m-%d %H:%M:%S')

You can do instead:

I18n.l Time.now, format: :myformat

with the myformat format defined in a locale file, say config/locale/time_formats.en.yml:

      myformat: '%Y-%m-%d %H:%M;%s'

The format string supports all the same format options as strftime, so conversion of your existing strftime code should be completely trivial.

It is important to pass a Symbol to the :format option of I18n.l, or it will try to interpret it as the format itself, and not its 'name' in the localization file.

Note: I18n.l has an alias I18n.localize, feel free to use it if you like to type.

When you are inside of a Rails view, you have another shortcut:

= l Time.now, format: :myformat

This is not all, yet...

It works for dates to:

I18n.l Date.today, format: :myformat

Event though it uses the same format name, it will use a different localisation key:

      myformat: '%Y-%m-%d'

Of course myformat is not such a great name for a format name ;). In a real application I would use something like compact, full, connfig, etc.

A couple of formats,:short, and :long are already provided, but I wouldn't rely on them and I suggest you define by yourself any time/date format that you intend to use inside of your application.

Lately, my prefered Postgres distribution of choice for OSX is Postgres.app.

Its very easy to download and install (just drag-n-drrop, like most other OSX Apps), no need to wait for it to compile, and it comes with a nice menubar icon for control.

In its default configuration it only listens on a port, but not on a unix socket. The problem is, Rails recipes with postgres create a config/database.yml file that assumes a socket presence.

Of example:

✗ rails new test1 -d postgresql
      create  README.rdoc
Your bundle is complete!
Use `bundle show [gemname]` to see where a bundled gem is installed.
✗ cd test1
✗ rake db:create
could not connect to server: No such file or directory
        Is the server running locally and accepting
        connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?

This problem was bothering me for a while as I tried to use rails_apps_composer to bootstrap new applications and it was failing on those database errors.

I didn't want to mess with Postgres.app configs, as I suspected they'd be overwriten on each version upgrade, so at first I tried to somehow trick it to stop and let me replace the config/database.yml file in time. The solution turned out to be much simpler though.

The Rails Postgres driver recognizes standard Postgres environment variables, one of which is PGHOST. When set to localhost Rails will go for the port instead of the Unix socket, even if there is no host: localhost setting in the YAML file.

✗ PGHOST=localhost rake db:create
✗ _

So just add export PGHOST=localhost to your shell start file, e.g. ~/.zshrc and you are set.

Im actually went further with it, and now I have shell aliases to reset postgres env config, configure it for localhost, or read current application Heroku configs and pre-set Postgres environment for a direct access to Heroku db, but that is a topic for another blog post.

The are multiple ways of configuring your Rails application for different environments (e.g. staging, production, etc). One of the popular ones is through environment variables. For example Heroku uses this type of configuration extensively.

One of the benefits of it is that configuration values are never stored in the source control system, which improves security (for sensitive configuration parameters) and also makes it easier to try different configuration setups w/o changing the sources or re-deploying the application.

On the other hand writing (ENV['PRIMARY_DOMAIN'] || "myapp.com") every time you need your domain string becomes cumbersome pretty fast, not to mention duplication and having the default repeated all over the place.

A competent programmer will of course only do this once, and re-use the value everywhere. Something like this:

PRIMARY_DOMAIN = ENV['PRIMARY_DOMAIN'].presence || 'myapp.com'
S3_BUCKET = ENV['S3_BUCKET'] || raise 'missing S3_BUCKET'

But it quickly becomes complicated, and again, quite a bit of similarly looking code that begs to be refactored out.

constfig is something I extracted from a couple of my latest projects. It allows you to do just that, have a configuration parameters stored in constants with values coming from environment variables and ability to provide defaults or have required parameters (i.e. fail if missing).

I just released version 0.0.1 of constfig to rubygems. Sources are of course on github.


Add this line to your application's Gemfile:

gem 'constfig'

And then execute:

$ bundle

Or install it yourself as:

$ gem install constfig


There is only one function provided by the gem: define_config.

With a default (optional variable)

You can call it with a default, like this:

define_config :DEFAULT_DOMAIN, "astrails.com"

In which case it will first look if ENV['DEFAULT_DOMAIN'] is available, and if not will use the 'astrails.com'. A constant DEFAULT_DOMAIN will be defined.

Without a default (required variable)

Or you can call it without the default:

define_config :DEFAULT_DOMAIN

In which case it will raise exception Constfig::Undefined if ENV['DEFAULT_DOMAIN'] is not available.

Variable type

One last thing. Non-string variables are supported. If you provide a non-string default (boolean, integer, float or symbol), the value that is coming from ENV will be converted to the same type (using to_i, to_f, and to_symbol). For the true/false types "true", "TRUE", and "1" will be treated as true, anything else will be treated as false.

In the case of required variables, you can supply a Class in place of the default, and it will be used for the type conversion. Like this:

define_config :EXPIRATION_DAYS, Fixnum

For boolean variables you can supply either TrueClass, or FalseClass.

Existing constants

This gem will not re-define existing constants, which can be used to define defaults for non-production environments.

Rails on Heroku

There is one caveat with Rails on Heroku. By default Heroku doesn't provide environment variables to your application during the rake assets:precompile stage of slug compilation. If you don't take care of it your application will fail to compile its assets and might fail to work in production. To take care of it you can either use Heroku Labs user-env-compile option, or (and this is what I'd recommend) you can use development defaults during assets:precompile.

For example in Rails you con do this:

if Rails.env.development? || Rails.env.test? || ARGV.join =~ /assets:precompile/
  DEFAULT_DOMAIN = 'myapp.dev'

define_config :DEFAULT_DOMAIN

In development and test environments it will use 'myapp.dev' ad PRIMARY_DOMAIN, but in production and staging environment it will fail unless PRIMARY_DOMAIN is provided by environment.

NOTE: make sure those configuration variables are not actually used for asset compilation. If they are, I'd go with user-env-compile.

Managing environment

You can use the dotenv gem to manage your ENV.

The Rails 4 Way on Leanpub.com

We are proud to announce that our own Vitaly Kushner co-authored the new edition of 'The Rails 4 Way' together with Rails legend Obie Fernandes of Hashrocket fame.

'The Rails 4 Way' is the latest edition of the most comprehensive, authoritative guide to delivering production-quality code with Rails 4.

Pow is great. The single thing that bothered me was problems with using debugger while pow'ing away.

Did you ever put a debugger into your controller, connected with rdebug, hit refresh but it didn't stop?

The problem is most probably with POW_WORKERS setting. You see, by default, pow will start 2 ruby processes per application.

Since direct console access is not available when using pow, you have to use rdebug instead. Usually it means something like this added to config/environments/development.rb:

# to use ruby debug with Pow do the following:
# echo export RUBY_DEBUG_PORT=20000 >> ./.powenv
# to connect:
# rdebug -c -p PORT_NUMBER
  Debugger.start_remote nil, ENV['RUBY_DEBUG_PORT'].to_i

Then you can restart your pow application and run the following command line:

rdebug -c -p 20000

Once you get "Connected." back you know that your rdebug has connected to some ruby process and is awaiting breakpoint hit.

The problem is that pow by default starts 2 ruby processes per application, and so only one of them will be able to bind to the port 20000. Which in turn means that only requests being processed by this process will get a chance to be stopped in debugger. So on average only about 50% of your requests will hit the debugger.

The solution is fairly simple. Just add the following line to your ~/.powconfig file:

export POW_WORKERS=1

Then restart pow.

Note: I mean the whole pow server, not just your current application. I'm using the excellent powify gem for this:

gem install powify
powify server restart

From now on you will get only one pow process per application and never miss a breakpoint again.

Rails Conference 2012, first time in Israel, was a great deal of fun. Lot's of presenters both local and from all over the world, well, more like from all over the world of Rails. There were talks from Github, Heroku, Engine Yard, Gogobot, Get Taxi and lots and lots of others. Solid organization from Raphael Fogel People and Computers guys. Hordes of interesting people to talk to, nice and abundant food and coffee, lots of great content from the speakers and to sign off the day Github guys invited everyone to an open bar drinkup event.

We gave 2 talks, Vitaly's "Performance - When, What and How" and Boris' "Rails Missing Features". Check out slides and videos of those talks.

nanoScroller.js - jQuery plugin to implement OSX Lion-styled scrollbars for your website.

strong_parameters gem allows you to "test drive" the new way that Rails 4 is going to treat parameters security. attr_accessible and friends are being deprecated.

celluloid.io interesting approach to multithreaded programming for Ruby.

Letters - new take on debugging logging library for Ruby.

showcase of 40 pricing tables and signup pages can help with with some inspiration for your pricing page.

lenticular.js - Tilt controlled images.

Repo.js - light-weight jQuery Plugin that lets you easily embed a Github repo onto your site.

FullCalendar is a jQuery plugin that provides a full-sized, drag & drop calendar with events etc.

tl;dr Legal - easy summaries of open source licenses.

CCMenu - OS X menu bar application to pull build status of your projects. Support many different CI backends.

UPDATE [30 Apr 2013]: The new, updated and faster version of this blog post covering Ruby 1.9.3 patchelevel 392 and railsexpress patch set.

I knew that there are various Ruby patches available but I've never tried them as I didn't want to waste time for something that I thought I don't really need.

Then I found out that rvm comes bundled with patches ready to be applied, so I'm just a simple command line away from having a patched Ruby. Don't know how I missed that before.

Finally, there is a Rails Conference here in Israel. Long overdue. We're sponsoring it and giving one keynote and one lecture.

I recently switched to ruby 1.9.3 as my deafult ruby verison, and suddenly some of my scripts started to fail in some funny ways.

One of the latest ones was the script that was supposed to change 'updated' timestamp in a YAML formatted file. Instead of the current date it started to spit out binary strings.

The problem is quite complext but the fix is simple...

I did an overview presentation about the current state of real time web and server-push technologies at the Israely DevCon 2012 conference.

Below is the transcript of the talk (actually more like a talk plan ;)

There is also a [pdf version for download][pdf].

It is in English as this is the way I usually write down my presentations, although the actual talk was delivered in Hebrew.

Check out the video of the talk on YouTube or embedded here. And if you more of a reader then viewer you can check out the slides with sort of transcript below.

Given that module Foo is defined elsewhere what is the difference between this snippet:

class Foo::Bar

and this:

module Foo
  class Bar

Answer inside ;)

My Vim-fu improved a lot in the last couple of years.

Part of the reason is that working on [dotvim][dotvim] forced me to dive deeper into it, but thats not the whole story.

I think a much bigger reason is that I decided to systematically work on improving it.

One of the tricks I use is to have a list of Vim tricks and shortcuts that I'm learning right now on my OSX dashboard.

I had a lot of things to do last Thursday, Feb-17. I met a friend from abroad 3am at Ben Gurion Airport and spent several hours talking before we went to sleep, signed a contract for developing killer web app at 1:30am, and finally gave a presentation at The Junction at 4:30pm.

Vitaly gave an interesting presentation about MongoDB at Database 2011 Conference.

MongoDB. NoSQL for SQL addicts.

Slides are here.

We presented on IGTCloud Ruby On Rails Day today.

Agenda was a bit different this time, not only technical presentations but also a few words about modern approach of building web applications.

Find the slides below.

I was working on tests for blender when I came upon a need to mock or stub a back-tick operator e.g.:

`shell command`

Apparently this is just a shortcut for calling Kernel method :`.

A few days ago I gave a presentation about Ruby for Sayeret Lambda discussion group.

The title was "Ruby is an acceptable lisp" but the message is better served by "Ruby is Better then Lisp ... sometimes" :)


Supports ERB and HAML for now, vote on site for more formats.

Beautifully crafted, totally free and it's kinda fun.

I've just read "Do You Believe In Magic?" and the following quote resonated particularly well:

"It's not magic. There is no magic involved. It's just, if you never learnt Lisp, then you never learned to program, and Ruby's power is exposing a deficiency in your skills."

We just started a project for a client that involves Cassandra.

If you've been living under a rock and don't know what Cassandra is let me tell you :)

Cassandra is a "second-generation distributed database" that was built for web scale.

Its is one of the many distributed nosql databases that appear everywhere lately like mushrooms after a heavy rain :).

What sets Cassandra apart is that it comes from a recognizable entity - Facebook.

But I digress.

This is not meant to be a Cassandra introduction, there are enough of those on the net. I Just created a new nosql section on this blog where I'm going to post various tidbits of information about cassandra (and probably others) as I learn them while working on this new project.

Here is the first one: Cassandra gem is just an installer

Yeah, I know, MVC is the "Only True Way™". But sometimes, just sometimes, you need your link_to or html helpers working in the model.

For example, sometimes the cleanest way to implement something is to have to_html in the model (widgets anyone?).

Doing this will most probably require generating some urls, and you need a controller for that. Usually I solved this by passing controller to the to_html function, but it always felt wrong.

This is going to be the first part of a blog post series about javascript widgets.

First type I'm going to cover is Popup Widget. Sometimes it's called Popin Widget because there is no actually new window that pops up, instead the content is shown IN-side a current page. The idea is quite simple: you provide some html/js snippet to other sites. They put it into relevant place, and you have some functionality of your site running there.

Clicktale is a service that allows you to record and later playback behavior of your users while they are using your site. And Rails is Rails, you know.

And those two are getting along just fine, until the user logs in. After that clicktale service is cut out of the html pages this user gets and can't record the session. But it just started to get interesting...

Wouldn't it be cool if you could just require "http://my-host/my-lib.rb" in ruby?

Now You Can! Using our "http_require" gem! :-)

I was the last person in our company working with ERB to render templates. While all the rest switched to HAML. At the beginning it was quite hard for me to read HAML comparing to ERB. HAML looked for me like some completely alien thing with weird percent marks all over the place and the significant whitespace never did it for me. On the other hand ERB felt like warm home after years we spent together.

Until I did the switch.

In the process of installing Mephisto I've got a problem with image_science gem.

It installed OK but when trying to require it the was a problem with RubyInline compilation:

On one of our projects we needed to do some caching for an action with an expensive db query. Fragment caching took care of the rendering but we needed a way to skip the db if we have a cache hit. And checking for an existence of the fragment file in the controller just didn’t seem right.