yon-line

Trimming the Fat From Your Controllers - Slides

| Comments

Today I gave a talk on How to trim the fat from your controllers at #railsisrael.

It was a real fun conference and it was awesome meeting lots of passionate Ruby devs in Israel.

Hope you enjoyed my talk - would love to get feedback.

I will post a more indepth look at improving controllers and extracting code soon and I’ll update here when it’s up.

So follow me on twitter @YonBergman and subscribe to my RSS

Writing an Alfred Extension With Ruby

| Comments

Another month another side project.

TL;DR - I created an Alfred extension in Ruby, it’s easy you can fork my base to create your own.
If you just want the Spotify finder extension download it

I love Alfred,
It’s a great tool - I use it for tons of different stuff: Running programs, controlling my music, basic math and as a file manager. A couple of months back we wrote a small extension at work that talks to Flobot our bot that manages the TVs in the dev rooms so you can command it from Alfred. It was a nice experience but I didn’t get the chance to do anything else since then.

Yesterday someone approached me at work and asked me if there’s a way to control the Spotify player from Alfred. I showed him the extension that’s hosted on the Alfred site. He thanked me, but then asked if theres a way to actually play a specific song - I liked that idea and couldn’t find any extension that does, So I wrote one.

I knew that what I wanted to build was a simple extension that receives a track name in the Alfred query and just plays or queues it into your Spotify app, simple.

play [track name]

I started by checking the Spotify API and quickly found that they have a really nice API for searching for tracks and that it responds with something called a Spotify URI which is a unique identifier for a track, album or artist ALA spotify:track:6ZWn1MVUaBH2HNQobhMYeE

I went on to see what ways I have to control the Spotify player, I found that it supports some very basic commands in AppleScript and that one of those commands is a play command that receives a spotify URL and plays it.
COOLNESS.
There was also something called Libspotify but it was a lot more complex to set up and wouldn’t be relavent in an Alfred extension.

So after testing both API’s seperatly I started working on integrating them. I checked if there was an easy way to send a http request from the AppleScript so I could just query Spotify from the same script that controls the player I couldn’t find an easy way to so I decided to try and write the script in Ruby.

I wrote a small Ruby script that takes a search query as the program argument, send a http request to the Spotify API and parses the first track URL from it. I then found the supported command to run an AppleScript from the command line and using Tempfiles integrated both parts.
I now had a script that searched for a query, got the URI, created a temporary AppleScript that when run using the osascript command plays the track that was found.

Success!

The only thing left was to package it into an Alfred extension.

I wanted my extension installation to be as simple as possible, Alfred extension are always really easy double-click installs and I didn’t want the fact that I used Ruby to make it any worse.

I found a cool extension that also ran Ruby - the conversion extension script and decided I liked the way they got around this issue - They created a temporary ruby file with the contents of the script, ran it and then removed it.

So I started working on a shell script that unloads my script into a tmp ruby file, runs it and deletes it. To make that shell script I wrote a third ruby script wrap.rb that will help me in development - what it does is take a ruby script and create a shell script from that that when run reopens the ruby file and etc. I started writing code that read a Ruby script and tries to compress it into a single line without quotes until I figured out I’m heading towards the wrong solution. I found that I can use a HEREDOC to write a multiline string into a file in the shell :)

1
2
3
4
5
> cat FILENAME <<EOF
  this  
  is   
  SPARTA!  
  EOF

So my wrapper script is real simple, it just reads the content of the original script run.rb and wraps it in 5 lines of shell that create a tmp file, dump the content into the tmp file, run it using /usr/bin/env ruby $filename and then delete it - that’s it.

To ”build” the extension all I have to do is run the wrap.rb file it converts the run.rb file into an extension.sh file which I use to create an Alfred extension.

The only caveat is that I assume Ruby installed on the system which is builtin in the latest OSXs and I don’t rely on installed gems.

In summary

The script is easily replaceable and I can use this system to write more Ruby Alfred extension - and you can to. Just check out the GitHub repo.

You can download the extension or
Read the Readme and fork the code on GitHub

You should follow me on twitter @YonBergman and subscribe to my RSS


PS. 10 Bonus points if you checked what song I embeded earlier when talking about the Spotify API

Introducing ‘O RLY?’

| Comments

Today I scratched an itch, something that has been bugging me for quite some time now.

Sometimes I pull a new version of a project and try to run it only to get an annoying ‘Run bundle install…’ message or worse an app that starts running but then starts to spazz when you do anything just because no one told you that you needed to run rake db:migrate So I built a small gem to help me exactly with these issues :)

O RLY? or orly for short, is a simple utlitly gem you use to install git-hooks into your git repositories. Every time you either git pull or git merge (pull acutally runs a merge) orly goes over the changes and notifies you when there are any commands you need to run. It’s very unobtrusive, it doesn’t run any commands for you - I wanted you to be in controler and decide when and if to run them, it just tells you about them. Check out the code on the github page

Installation

Installing orly is really easy just run the gem install command once

[sudo] gem install orly

After you installed the gem just go to any git repo that you have and wish to install orly on and run

orly --install

You can always run orly --uninstall to remove the git-hook or orly -h to get help about orly.

Using RVM?

You might need to install the orly gem every gemset before you can install the git-hook

Secret Easter egg

You can also run orly -s or --speak and make the orly owl repeat what you say amazing progress :)

The LOLs

Some of the inspiration for ORLY (especially the installation method) came from another awesome utility gem called lolcommits, its a really fun gem that lets takes a picture of you each time you commit code and adds your commit message as text on the image. It’s really fun to have especially when pairing with an unsuspecting victim. Their installation process was really painless and also uses git-hooks. If you’re using a laptop at work or have a webcam install lolcommits you won’t regret it.

Scratch your own itch

One thing we as programmers need to do more is scratch our own itches - if something in your workflow bothers you, takes too much time, is too manual. FIX IT! either find a solution or write one. We have the abilities to write stuff like this to make ourselves happier and our work less crazy. This isn’t my first ‘band-aid’ and it won’t be my last, I enjoy building and sharing stuff like this and will continue to scratch away. Do it too, don’t let those itches become more start finding or building solutions now. Just make sure you’re scratching and not shaving yacks and go build stuff!

You should follow me on twitter @YonBergman and subscribe to my RSS

Why You Should Use Sass

| Comments

Today I want to talk about Sass, why I love it and why you should use it. Sass is a css preprocessor, meaning it’s a file format which you compile to css to be served along side your site. Sass comes in two syntaxes .scss and the older syntax .sass also called indented Sass, whenever you hear people talking about Sass they’re probably talking about the newer syntax. In this post I’ll be referring only to the .scss syntax.

Why I love Sass

Sass is what CSS should be, it has really good abilities that are really missing in CSS. After working with Sass for some time you won’t understand how css doesn’t include them built-in.

The 3 big things that Sass gives you are:

Nesting, Variables and Mixins

Nesting

Nesting is the ability to write your selectors in a nested fashion where you don’t have to repeat yourself as you go down the hierarchy of your style. It makes changing top sections of selectors painless and the css code more DRY and concise.

1
2
3
4
5
6
7
8
9
10
11
.user {
    color:              blue;
    .avatar {
        width:          50px;
        height:         50px;
        .selector {              // Compiles to .user .avatar .selector {
            position:   absolute;
            left:       0;
        }
    }
}

An awesome feature of nesting is the ability to reference self while nesting making pseudo-selectors and modifier class beautiful, to reference self inside a nested block you just write & while inside a block.

1
2
3
4
5
6
7
8
9
10
11
12
13
.btn{
    color: white;
    background: blue;

    &:hover{             // Compiles to .btn:hover {
        color: grey;
        background: lightblue;
    }

    &.warning{
        background: red;
    }
}

The last thing you can do with nesting is reverse nesting - adding a selector before current selector. This feature is amazing and you can do cool stuff with it like browser specific hack, site theming and much more.

1
2
3
4
5
6
7
8
9
.profile{
    .avatar{
        color: blue;

        .friends &{             // Compiles to .friends .profile .avatar {
            color: grey;
        }
    }
}

I use this to handle IE specific hacks, I just add a class to my <HTML> tag with the version of IE in question class='ie7' and then inside the code whenever I need to do a IE specific hack I just use reverse nesting

1
2
3
4
5
6
.profile{
    border: 2px solid #ddd;
    .ie7 &{
        padding: 25px;
    }
}

Variables

Variables is a pretty straight forward feature, in Sass you can define variables and use them later. This helps reduce copy-pasted variables like colors, sizes and strings. Variables are defined in this syntax $main-color: #ffeeff; and can be used just by using them instead of the constants you would normally use.

Sass also supports basic operations on variables like math operations, string operations and even color functions. Color functions are very cool functions that let you modify colors ever so slightly based on a base color instead of hard coding all the color variations, you can lighten a color by x percent, opacify or change hue - for a complete list of available functions check the Sass Reference

1
2
3
4
5
6
7
8
9
10
11
$main-color: #ffeeff;
$link-width: 50px;
a{
    color: $main-color;
    &:hover{
        color: lighten($main-color, 20%);
    }
    img{
        width: $link-width * 2;
    }
}

You can also do some very basic programming with Sass stuff like if and for which are really helpful especially helpful when you add the next thing Sass has to offer - mixins.

Mixins

Mixins are ‘functions’ that you define and can use across the system, they can be used in different selectors and you can pass in arguments. There are two different uses for mixins that I find, When you need a function shared across the site in several different contexts or when you define “private” mixins to help you manage your css and separate responsibilities better. Mixins let you treat your stylesheets as first-class citizens in your code base.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@mixin floaty($minimized-by-default, $side: left){
    float: $side;
    width: 300px;
    @if $minimized-by-default {
        overflow: hidden;
        width: 5px;
    }
}

.navigation{
    background: green;
    @include floaty(false);
}
.navigation.secondary{
    background: blue;
    @include floaty(true, right);
}

Mixins are priceless when you need to have cross-browser support, the time we live in right now has us using these amazing css tricks which aren’t always implemented in all the browser or if they are they’re wrapped in browser specific prefix. You can use mixins to help you use the stuff you want while not having to write all the prefixs every time. For example instead of writing -webkit-box-shadow... -moz-box-shadow you can now just write @include box-shadow(); and the mixin will take care of writing all the correct prefixes and if needed - change the parameters to fit each browsers quirks. But you don’t really want to right all these mixins for yourself, this is where Compass comes in.

Compass is a Sass library containing many of these helpful mixins for cross browser support and other handy stuff that are very helpful. It has almost everything you need to build beautiful stylesheets with cross browser support - something that if you tried know that gets messy very fast.

Why you need it?

The transition from css to Sass is painless - you don’t need to change any old files you already have in your system. Just rename your files from .css to .scss add a compiler (Compass is one, Rails 3.1+ is another) from then on just start using Sass’s abilities whenever you need them. This is a true smooth transition and probably the reason why the .scss syntax beat the old indented syntax. With Sass you can easily manage a system of plugins and shared library ‘code’ between different parts of your site and even between sites in a way which plain css can never do.

With Sass & Compass you can have better Cross browser support especially if you’re planning on using all the new ‘CSS3’ properties. Even if you’re not using new properties Sass gives you workaround for the basic stuff broken on IE - stuff like display: inline-block;

And most of all, Sass lets you treat your stylesheets as part of your code base, with the respect they deserve and with the power that you need. So go start using Sass and enjoy the power!

Alternatives

There are some other CSS preprocessors out there. I didn’t have the chance to use any of them, but people like to know about alternatives. Less is the biggest rival to Sass and is mature almost as must as it, Stylus is another alternative albeit a smaller one, there are several others but they are really niche. If you’re looking for a CSS preprocessor you should probably go with eiter Sass or Less.

Some Rails tips

  • If you’re using Rails >= 3.1 and the new asset pipeline you already have the power of Sass built in, just rename you’re stylesheets to .css.scss and you can start using Sass.
  • You should always try and avoid asset pipeline import command //require ./avatar.css - use Sass’s @import function instead this lets you use mixins and variable you define inside the files your import. If you use using asset pipeline’s require you’ll get the file compiled in place which isn’t that fun.
  • You can use Compass’s mixins inside your asset pipeline application. Just added gem 'compass-rails' to your Gemfile under the :assets group and add the following line to your application.rb file
1
2
config.sass.load_paths << "#{Gem.loaded_specs['compass'].full_gem_path}/frameworks/compass/stylesheets"

  • If you’re using an older version of Rails or just didn’t migrate to the asset pipeline you can use the compass gem to add support for Sass, Compass will not only give you Sass support but will also compile the files for you on the fly or when you want to precompile them all.

Hope this post got you interested in checking Sass out - you’ve got nothing to lose :)

You should follow me on twitter @YonBergman and subscribe to my RSS

Comparing Mobile Web Frameworks

| Comments

I wanted to share my recent experiences with building mobile web ui’s. I experienced working with three different methods of building mobile ui some of them during my day-time job and some on my weekend hacks. I’ll try to give the pros and cons for each method and framework and let you decide which ones fits your project best.

TL;DR - Mobile Web frameworks are cool, kind of like using Twitter Bootstrap. I’m gonna go with building without a framework for most stuff.

So as I said I got to work with 3 different methods of building a mobile web ui. The first one was building a mobile web ui for my weekend project Makom-tov. I actually wrote and rewrote the ui for that because I wasn’t really happy with the result. I first wrote it in jQtouch and then I rewrote in in jQuery Mobile (Just as it came out of beta). The other project was writing a mobile ui for my project at work eBay Go Together, this UI was designed by our awesome designer and I wrote it using no framework just regular HTML, CSS and Javascript.

Feedback on each method

jQtouch (link)

  • It’s kind of old and isn’t updated almost. :(
  • It’s a good framework to choose if you need iOS native looking ui out of the box.
  • It doesn’t customize that well.
  • I didn’t like its methods of describing elements and behaviours. (mostly using classes and conventions)
  • It’s methods of dynamically loading pages required to change stuff on the server side
  • Supporting RTL wasn’t fun but was ok
  • Even if you keep the standard UI it doesn’t look boring because its the native UI
  • Poor documentation - need to play around a lot to get stuff to work.

jQuery Mobile (link)

  • Amazing Documentation !!!
  • Nice standard ways to define and elements and behaviours via data attributes.
  • Awesome dynamic page loading.
  • Good support for themeing
  • Poor support for customizing the UI beyond the themeing
  • Did not have a fun time to support RTL
  • Default UI is device agnostic which means that it doesn’t look native on any device
  • Supports devices I don’t care about at all :(
  • Even if you theme it, it looks the same. Creating an ecosystem of boring apps - which makes me a sad panda :(
  • Looks like a plugin ecosystem is beginning to emerge

No Framework

  • You can do whatever you want !
  • Support only the features you need
  • You can achieve total customization
  • Making it look native take some work
  • There are JS and CSS libraries that might do some of the stuff and make it easier
  • Need to roll out your own JS to support behaviours that feel native
  • Smaller download for user - can minimize the most
  • Need to play around with a lot of iOS magic to achieve some stuff (icon, hiding bar and other)
  • A good resource for starting something like this is this article that was featured on HN a while back

What should I use?

The first thing to do when approaching development of a web ui is deciding what type of web ui you’re looking for. If you’re looking for a native ui or a customized ui, what’s the scope of your mobile ui, is there a desktop ui as well and other stuff.

Go with a framework if what you need is

  • Building fast and well. (think Twitter bootstrap)
  • Standard widgets and behaviours (lists, scrolling, swipes)
  • Semi-Native looking UI
  • Must support many devices

Go no mobile framework if your needs are

  • Very custom UI elements
  • Few standard widgets in page
  • You need O(100%) native ui for one platform
  • Like writing your own web/css/js

Some other frameworks for building Mobile UI

There are two other frameworks for building web ui. The first is Sencha Touch - while I didn’t get to work with Sencha myself I heard it is a good and solid framework that has many capabilities that other web frameworks don’t have. The down side of using Sencha is that it’s a completely different paradigm of building web, you are completely dependant on their APIs and design. There also some licensing issue with Sencha products - if it matters to you keep an eye open and check it out.

The other framework isn’t a mobile framework per se it’s a web ui framework with good support for responsive design (design that responds to your screen size and adapts). You’ve probably heard about it Twitter Bootstrap. Twitter bootstrap helps you set up an really solid ui very fast and that ui looks pretty good even on mobile devices (the picture at the top of the blog displays such a UI). It’s really good if you want the same overall feel between desktop and mobile. The problem with using Twitter bootstrap is the same as using Jquery Mobile, the ecosystem of ui’s that come out of it all look very similar and boring.

Building Mobile UI in Rails

If your app needs to have both a web ui and a mobile ui you will need a way to control many similar partials and templates There is a very cool way to manage when to display each type of site and also managing your views.

The basis for this method is on changing the mime type for mobile to differ from the regular desktop mime type. First add your new mime type in the config/initializers/mime_types.rb and then add a before_filter method that runs in ApplicationController or on whatever controller you need to support.

application_controller.rb
1
2
3
4
5
6
7
8
9
before_filter :mobile_override

def mobile_override
    user_agent_mobile   = request.user_agent.to_s.include? "mobile"
    mobile_override     = params[:mobile] == "1"
    if ( user_agent_mobile or mobile_override ) and !request.xhr?
        request.format = :mobile
    end
end

Once this filter is in place you need to start creating new templates and layouts to be rendered, each file that needs to have a mobile version should have a counterpart for the new mimetype. For example application.html.haml has a mobile counterpart application.mobile.haml the first one is displayed for desktop users and the second for mobile.

What about partials that are used in both versions? There are three ways to share partials between desktop and mobile. The first one is deprecated and messy and thats setting an explicit format in the rendered file’s name - for example

1
render :partial => "common/avatar.html", :locals => { :user => @user }

It’s the easiest because you only need to change the calls and not the file names, but this method doesn’t work for when you want the format to trickle down. Lets say our avatar partial uses another partial called photo like so

avatar.haml
1
2
3
.avatar
    %span.name= user.name
    != render :partial => "photo", :locals => { :image => user.photo }

In this case if from a mobile template lets say show.mobile.haml I call render :partial with a specific format once that partial tries to render the photo partial with no format specified it will look for a mobile format and raise an error.

The other way is passing :format => [:html] to the render function - but it didn’t work for me. (this is new in Rails 3.2)

The third way and the one I like best is removing the format from partials that are shared, meaning that in our example common/avatar.html.haml becomes common/avatar.haml and can be safely called from both formats. You must ofcourse change all the partials even the ones inside but in the end you’ll have a more organized code base app.html.haml are files that appear only in desktop app.mobile.haml only in mobile and app.haml are shared across both.

Well thats it - hope you learned something new - and go create a mobile version for your site, users are using their phones more and more to view the web.

You should follow me on twitter @YonBergman and subscribe to my RSS

My First Gem - Enumify

| Comments

I just published my first gem. ( Enumify )

TL;DR - I created my first gem in under one hour, it was fun and easy and you should do it to - Enumify (my gem)

It was an amazing experience - totally painless and easy.

You might remember an old post were I promised to create a gem out of my enum lib. Well last night I watched Ryan Bate’s Railscast about creating a gem and decided it was about time to go on with the idea an actually create the gem.

I created a new repo with the gem, created tests that cover all of the use cases, wrote documentation - and in less that an hour from starting I had it up and running in RubyGems.
A couple of minutes later it was running on Travis-CI (AMAZING) and running in my projects instead of the hardcoded code that I extracted the gem from.

I have to say that about a year ago when I created this lib and wanted to created a gem it seemed hard and scary but after going through it once - it’s really easy and fun seeing your gem up in rubygems and just adding it as a gem in your GemFile is really a good feeling.

So go - Make your own gem (and give mine a try)

enumify on rubygems.org


A little about the gem

The gem is called Enumify and I created it after understanding that a lot of times I have a enum like string attribute on my models but can’t really get the most out of it. 

The gem works on a basic string attribute of a model (lets say status for an event) and gives you validations and some functions to easily work and check it.

To use the gem just add it to your GemFile - gem ‘enumify’ 
after that just go to your model where you want to add the enum and call the enum function, it accepts a field name and an array of possible values  

class Event < ActiveRecord::Base
    enum :status, [:available, :canceled, :completed]
end
There are four things that the enumify gems adds to your model
  • Validation - The enumify adds a validation to make sure that the field only receives accepted values
  • Super Cool Methods - adds ? and ! functions for each enum value (canceled? - is it canceled, canceled! - change the state to canceled)
  • Callback support - you can add a x_callback method which will be called each time the status changes
  • Scopes - you can easily query for values of the enum

for a complete documentation on how to use the gem go to the Github page - https://github.com/yonbergman/enumify

 

Follow me on twitter @YonBergman and subscribe to my RSS

Dynamically Shrinking Titles

| Comments

Hey, I wanted to share with you a cool trick I found for creating shrinking titles in a web page.

My problem was that I had to implement a page which had a title which content was based on an eBay item name and I couldn’t control the amount of text in it. The design was it to fit a specific space in the page and be a certain size and color. The other thing that I really didn’t want my page layout to jump around because of the title.

My first solution was to try and integrate BigText into the page, but BigText isn’t a great solution and about 1 in every 10 titles came out cropped a bit on the side.

So here’s my simple solution for creating dynamicly shrinking titles which don’t distort the page’s layout.

I use an outer div to enforce the size that I want and make sure that even if the inner title is more than one line - you won’t see all the other lines and the page won’t distort. I then resize the title until it fits inside the space I want it to :) 

HTML (HAML) - The html for the page is really straight foreward. Just wrap your header with a div

 

CSS (SCSS) - The css is really the trick here, I set the size of the text at my desired size, but wrap it with a div that hides any of the text that exceeds the desired height & width of the title. I also set the line-height of the text to my desired height so that each new line takes a specific known size.

JAVASCRIPT (Coffeescript) - The javascript is pretty straightforeward it checks that the title’s height isn’t larger than it’s parents’s height - meaning that it isn’t breaking into two lines. Then I try decreasing the font-size until the text fits into the container.

I’m using HAML, SCSS & Coffeescript and so should you, it makes the code look 10 times better.

If you need a book for starting with Coffeescript check this one out. CoffeeScript (Prag Prog)

—– Update —– 

Someone asked me for a demo so here it is - Demo page

So You Want to Start Using Rails?

| Comments

Some people have recently asked me about starting with Rails, most of them don’t know Ruby or Rails and some don’t even come from the web world. At work they also asked me to create a list of reading material for our new guy. So I worked on that and though about all these other people who want to start with the web and with Rails and decided to put this list - reformated up for your pleasure.

Quick note

The Rails enviroment is a fast changing ecosystem this post was written on June 2011 and I can’t vouch how relevant it’ll be several months from now.
If your’e going to start with Rails right now I would recommend using Ruby 1.87 and Rails 3
Ruby 1.92 is new and it’s nice but a lot of gems have some problems (especially working with rvm)

Rails Setup

The first thing to do is read the Rails Guide on Getting Started. It explains all the basics and its not to hard to go over.
After that I suggest reading some more guides and mostly try and write your own small site. a blog engine, a todo List, a restaurant rater…just build something.

Now most Rails guides will show you how to use Rails pretty much as-is, meaning that they use only the built in stuff in Rails. 
I found that there are a lot of alternatives to stuff built-in in Rails that are easier to use than the defaults.
Quick definition - gem - is a Ruby software library.

  • HAML not erb - for a better templating system that works for you instead of the other way round (link)
  • SCSS (SASS) not css - because css is a pain in the ass to do right and SASS solves it (link
    I prefer to use SCSS because it’s complient to css
    Compass - a gem for working with scss/sass which has an amazing collection of prebuilt mixins. (link)
  • RSPEC not rails-test - Much better testing framework (link)
    Factory Girl , not Fixtures - For built in test data (link)
  • Jammit - to bundle your assets for production. (link)

For each of these you can probably find a guide or even a RailsCast and you should use them.

IDEs

There are currently several IDEs you can use to write Rails

  • RubyMine - my choice for editor. really nice, has basic refactoring and supports everything you need in an IDE (link)
  • VIM - with dotvim, really makes your vim a small ruby editor with git support and a lot of things (only if you like vim) (link)
  • Aptana RadRails - an eclipse extention for rails, last time I used it - it wasn’t so good but still worth checking out (link)
  • Textmate - A good text editor for Mac, Haven’t used it but most rails’ers use it (link)

Javascripts

Instead of using the built in system of autogenerated Javascripts created by Rails, I recommend using your own Javascripts that you’ll right completly indepentant of the Server.
I recommend using jQuery (link) as the basic helper framework and on top of that use JavascriptMVC (link) for helping you create a more organized and clear javascript system.
There is a lot to say about  including javascript in your site and I’ll probably write a post about it someday :)

Books

I really like books from the Pragmatic Programmers and as a rails starter book I definitely recommend - Agile Web Development with Rails
I read the 3rd edition Agile Web Development with Rails, Third Edition back when I started which talked about Rails 2.3 and this 4th edition is about Rails 3 and suppose to be even better :)

I also recommend Metaprogramming Ruby once you played a bit with the language it lets you understand a lot about how stuff works and how to build your own cool stuff.

In any case just search for Rails or Ruby and I’m sure you’ll find some more books.More books

Other Guides

The official rails guide - http://guides.rubyonrails.org/ - pretty good and comprehensive 
RailsCasts - awesome video tutorials on tons of subjects (I don’t have list of good episodes) http://railscasts.com/
and Rails for Zombies - http://railsforzombies.org/ - Haven’t gone over it but heard it was good.

One last note about ruby, It was written in Japaenese so a lot of basic functions are there in the String class or the Collections class but have a different name from what you’re probably used to.
For example to make a string lower case instead of str.lower_case or something like that its down_case.
I just google “ruby array” or “ruby string” when I need to find something that I need
:)
Enjoy Railsing :)

How to Get Someone’s Attention Without Disturbing Everyone in the Office

| Comments

In the past week or so we started working with headphones on in the office, our team just grew from 4 to 5 people and that meant that the noise in the room grew exponentially and it was getting hard to concentrate.

That created a new problem for us - How do we get the attention of the person sitting across the room from us without disturbing everyone else?.
I know that when someone shouts for someone else I always turn around and take off my headphones just to hear a ‘No, not you’ - who hasn’t?
What about throwing stuff…? that’s also problem because after some time you run out of stuff to throw :)
We tried to use an IM but we couldn’t agree around the office which one to use (we’re spread through all 3 of the major OS’s so that doesn’t help it).
So I though wouldn’t it be cool if I’ll have a way with one button to pop up a message on that persons screen without having everyone else jumping and dancing around?

Mr Cheerful flickr.com/photos/lachlanhardy/287563201/
‘Why would you want to annoy him?

I found a neat little setup and wrote a small ruby script that enables me to do just that.

I already had Growl installed from using autotest so I decided that it would be cool to use that as a notification system. I also found out about Notify.io which is a cool server for web notifications for growls.

Setting up a “master account”

Go to Notify.io sign in with your google account (assuming you want to set up the master account under your name - it doesn’t matter much this account can control the name and other stuff for the account that we sent through messages)
Go to Settings, check Yes, I want to send notifications with this account
and fill out the details with whatever you want I called ours Team-Notifier.
Copy the API KEY aside you’ll need it later and save.

Now you can start setting up everyone’s computers - start with your own and you’ll be able to send notifications from yourself to yourself.

The setup

 On each computer I installed a growl client and the Notify.io adapter

  Mac - has the original Growl and you need to install the latest Notify.io program (notice that the one linked to on the home site is an old one) 
  Windows
- I installed Growl for windows which awesomely has notify.io support built-in.
We then configured a Notify.io account by signing in with the person’s google account and then downloading the
Default Desktop Notifier - Listen URL from the Outlets tab,If you already installed the Notify.io adapter or just Growl for windows double clicking the file should set the connection to notify.io

Send a message to that computer and go in Notify.io to the Sources tab (If you don’t have the script installed yet you can send a test message from the master account’s settings tab but only to yourself)
hidden in the right side of the screen is a button for approving a new source - click it. Now you approved your account to get messages from your master account.
Messages should now flow to your growl on your computer, I usually send two test messages because sometimes the first message changes to show that the computer will now get messages and only the second works.

The Script

I also wrote a smal Ruby script to enable people to send Nudges (~pokes) and message to the other people’s growls.
It’s a pretty small Ruby script and it only needs basic Ruby installed on your machine. You can also probably translate this to any other language
but if you wan’t to learn some ruby check out this book from PragProg Programming Ruby 1.9: The Pragmatic Programmers’ Guide (Facets of Ruby)

Just download this to any directory you want and start sending messages to your team

If you don’t want to use my Ruby script you can also just send the messages any other way using simple POST commands - read the Notify.io developers guide

Other cool stuff

One of my team members wrote a small Vim plugin that enables him to send these pings right from his totally pimped out Vim setup.
I created a directory inside my windows programs list with shortcuts to everyone’s names - that enables me to windowkey-type name -send  nudge  which is less awesome than using vim but still pretty nice.
We want to create a visual program so that you’ll have a list of people’s icons on huge buttons and you’ll be able to click them to message them :)

 

If you have any question or problems with this setup just ask and if you have ideas or suggestions i’d love to hear them.
I’ll try and post a follow up in a week or two to tell you how it went.

Enums in Rails

| Comments

While working on a subset of new stuff at work it became apparant that some of our classes could really use Enums.

For this post we’ll go with the example of a User model that has a role which can be either Admin,Moderator or User.

We started with the most basic thing which was a simple model with a string column that represents the role, but we wanted some easier way to handle the validation and integrerty, so we read around on the Internet (mostly Stack Overflow - awesome site :) ) and we saw several best practices for handling enum, the most ‘comprehansive’ was on Five tips for developing Rails Applications #3. Basiclly the suggestion we collected was to use rails’s validates_inclusion_of to validate and to overwrite the getter and setter of the attribute to translate to and from symbol so that in your application you always work with symbols but in the DB it will be save as regular strings.

We also wanted a bit more from our enums, we wanted the option to view all availble elements of the enum and we wanted some shorthand methods we know are really usfull from exprience (admin? to check if current user object is an admin and admin! to change the role of the current user object to admin) and we needed an option to have callbacks in some of the enums where each time the value changes a function is called.

And on top all of that we wanted an easy way to get all of this without too much Copy Paste of code. We wanted it declared in a Railsy way inside the model.

So I sat out and wrote this cool new enum helper:

Here is how you declare and use an enum in an existing model

The code to make it work in your own project i’ll post tommrrow morning after i’ll try and gem it or something nice. If I don’t understand how to do it i’ll just post the raw code in this post.

Good week and happy hacking

- Yon