How to Create a NSNumberFormatter Singleton in Swift

This is the third post and screencast in a series I’m doing on Swift development.

Source code examples are available on GitHub

Singletons are a popular design pattern in programming. If you are new to Swift, you may be wondering how you can create singletons in Swift. In Objective-C, you might have tried Grand Central Dispatch‘s dispatch_once to create a singleton. Well, the other day, I came across a situation in Swift that I thought would be a good example of using a singleton.

I needed to use the NSNumberFormatter class to change an integer like “15” into a currency like “$15.00” for a table view I was displaying. Because initializing an NSNumberFormatter can be an expensive operation, I didn’t want the performance of the app to be affected by this, especially if I was going to be using the same NSNumberFormatter configuration throughout the app. So, I decided to use a singleton.

Now, there’s a great stack overflow post all about the different ways to create a Singleton in Swift, however, it doesn’t provide an in-depth practical example and since NSNumberFormatter is a class that gets used a lot, I thought I would share an example of using these patterns with this class. Ok, let’s get started.

First, we’re going to import the Foundation library.

import Foundation

Then, we’re going to declare a class called CurrencyFormatter, which is going to inherit from the NSNumberFormatter class.

class CurrencyFormatter: NSNumberFormatter {

In order to inherit from the NSNumberFormatter class, you have to implement a required init function. All we do is just call the same function with super, and then the pass the aDecoder parameter to the function. This isn’t important to our problem but it’s required, so you can mostly ignore it.

required init(coder aDecoder: NSCoder) {
  super.init(coder: aDecoder)

Override Init()

Now, we are going to override the standard “init” function, so we can set some default values on initialization. Inside the init function, first we need to call the “super.init” function. Next is code to make the currency formatting work correctly.

override init() {
  self.locale = NSLocale.currentLocale()
  self.maximumFractionDigits = 2
  self.minimumFractionDigits = 2
  self.alwaysShowsDecimalSeparator = true
  self.numberStyle = .CurrencyStyle

Type Property Constants – version 1.2 or above

If you’re using Swift 1.2 or above, we’re almost done. All we need to do is declare a type constant property. To declare a type constant property on a class, we use the “static let” keywords and call it sharedInstance and then we’ll initialize it to an instance of our CurrencyFormatter class.

static let sharedInstance = CurrencyFormatter()

Now our singleton should be ready. Here’s the final code.

import Foundation

class CurrencyFormatter: NSNumberFormatter {
  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  override init() {
    self.locale = NSLocale.currentLocale()
    self.maximumFractionDigits = 2
    self.minimumFractionDigits = 2
    self.alwaysShowsDecimalSeparator = true
    self.numberStyle = .CurrencyStyle
  // Swift 1.2 or above
  static let sharedInstance = CurrencyFormatter() 

NSNumberFormatter has a method called “#stringFromNumber” and all we need to do is call “#stringFromNumber” on the sharedInstance singleton and pass in the number. So, we’ll just pass in 20 and then we’ll unwrap the optional so we can see it.

println(CurrencyFormatter.sharedInstance.stringFromNumber(20)!) //$20.00

You can see now that our number is formatted to $20.00 and if we copy this and change it to 50, you can see it works as well.

println(CurrencyFormatter.sharedInstance.stringFromNumber(20)!) //$20.00
println(CurrencyFormatter.sharedInstance.stringFromNumber(50)!) //$50.00

Before Swift 1.2, Class Variable Properties and Nested Structs

If you’re using a version of Swift below 1.2, you can’t actually declare type constants on reference types like classes, so we’ll have to do this a different way. Go ahead and remove the type constant we created.

This time, we’re going to declare a class variable property, which we’ll call our sharedInstance. But instead of initializing it, we’re going to declare it as a CurrencyFormatter type and then we’re going to declare this class variable as a read-only computed property.

class var sharedInstance: CurrencyFormatter {

A computed property means instead of storing a value for this property, it just computes it every time that it’s called. In this case, it means we have to return an instance of CurrencyFormatter every time that this property is called. However, we can make it return the same instance by creating a singleton.

First, we’re going to declare a struct inside of this property. We declare a struct called Static.

class var sharedInstance: CurrencyFormatter {
  struct Static {

Structs in Swift are value types and in versions below 1.2, value types can have type constants which will allow us to create a Singleton of our CurrencyFormatter class. We’re going to declare it a type constant using static let, and then call it instance and then initialize it to an instance of our currency formatter class.

class var sharedInstance: CurrencyFormatter {
  struct Static {
    static let instance = CurrencyFormatter()

Then we need to return our Static.instance property (and singleton) at the end of the computed property.

class var sharedInstance: CurrencyFormatter {
  struct Static {
    static let instance = CurrencyFormatter()
  return Static.instance

Here’s the final code using the class variable and nested struct.

import Foundation

class CurrencyFormatter: NSNumberFormatter {
  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  override init() {
    self.locale = NSLocale.currentLocale()
    self.maximumFractionDigits = 2
    self.minimumFractionDigits = 2
    self.alwaysShowsDecimalSeparator = true
    self.numberStyle = .CurrencyStyle
  class var sharedInstance: CurrencyFormatter {
    struct Static {
      static let instance = CurrencyFormatter()
    return Static.instance

And now our numbers are formatted again, so we’re getting the correct currency formatting.

println(CurrencyFormatter.sharedInstance.stringFromNumber(20)!) //$20.00
println(CurrencyFormatter.sharedInstance.stringFromNumber(50)!) //$50.00

More to Learn

If you have found this information useful and would like to learn more, please sign up for the Swift newsletter below and I will send you updates when new posts and videos become available. You’ll also receive access to my video tutorial “Advanced Swift Arrays”.

Swift var vs. let – Screencast

My latest screencast is now available! This time I cover var vs. let in Swift. Topics I cover include:
– The difference between Var and Let
– Examples of variable values types like Strings and Ints
– How properties of reference types, like Classes, are affected
– I show an example using multiple classes and properties including inherited properties
– I demonstrate how properties of constant values types like Structs and Arrays cannot be change

This screencast is a part of a series I am doing on Swift development.

Introduction to Swift Arrays – Screencast

My first screencast on Swift development covers an introduction into Swift Arrays. This is the first screencast in a series I’m doing on Swift development. Here’s some topics that I cover in this video:
– How to create an array in Swift
– Declaration and Initialization of arrays in Swift
– Retrieving an item from an array
– Adding to a Swift array
– Iterating over the items in a Swift array

The topics in this video cover come from my post on arrays in “Swift for Rubyists”.

Swift for Rubyists: Dictionaries

This post is the second in a series I am doing on Swift for Rubyists.

Forgive me for the lines that wrap on this one. I did the best I could to try and format them on one line, but all of the examples from this post are available as a playground to download at this repo.

Update: Apparently, my changes to fix the “<” & “>” symbols missing in the examples didn’t save. Fixed now.

Swift Dictionaries

Swift Dictionaries are equal to Hashes in Ruby. Like Swift Arrays, Swift dictionaries are like dictionaries/hashes in most modern programming languages including Ruby. Although Ruby hashes and Swift dictionaries share many similarities, there are some areas where their behavior is very different.

Swift Dictionary Declaration and Instantiation

Declaring a Ruby Hash, like an array, is very simple.


Just like arrays, there are three different ways to declare a Swift Dictionary. In the first two ways, you must declare the type of keys and values before you instantiate the dictionary:

var swift_dict: Dictionary
var swift_dict_again: [String: String]

It is important to note that when declaring a Swift Dictionary in these first two ways, you must declare a type for both the key and value. In Ruby, any object can be a Hash key, but you have probably most often seen them as symbols or strings like the following examples:

{:key => "door"}
{"key" => "door"}

In order to be used as keys for a Hash (make it “hashable”), Ruby requires objects to implement “#eql?” and “#hash” methods. Strings and symbols both do these by default in Ruby.

Swift dictionary key types are the same way. Swift requires dictionary types to implement the Hashable protocol, which requires two methods “#hashValue” and the “==” operator. Strings, Int, Bool are all hashable types by default in Swift.

So, if you ever felt adventurous, you could create your own Swift type that implements the Hashable protocol that you could use as a Swift dictionary key. That technique is beyond the scope of this post.

Swift Dictionary Literals

There are Swift Dictionary literals. A Swift dictionary literal is very similar to Ruby’s hash literal. You are probably pretty familiar with this as it is found all throughout Ruby web frameworks like Rails:

{:key => "value"}
{key: "value"}

The syntax for a creating a Swift dictionary literal is slightly different, but very important. We lose the curly brackets and signature “fat arrow”, move the colon (depending on which Ruby syntax you choose) and add square brackets.

In Swift, curly brackets, {}, are very important. Swift uses curly brackets to define functions and closures. Swift uses square brackets for dictionaries. Here’s a Swift Dictionary literal:

var dictionary = ["key":"value"]

Like Swift array literals, we do not have to declare a type for the keys and values of the dictionary because Swift uses type inference to infer the kinds types for the keys and values. In this case, and

However, as I pointed out in my post on Swift Arrays for Rubyists, you must use literals in Swift carefully.

For example, let’s say you wanted to set the swift dictionary you created above to an empty dictionary. You would do the following:

var refrigerator = ["milk":"1%"]
refrigerator = [:]
println(refrigerator.isEmpty) //true

You might think that “[:]” is just the literal way of creating an empty dictionary. It is not. If you have imported Objective-C’s Foundation library, it will actually compile, but it creates an NSDictionary, not a Swift Dictionary. Here’s an example:

import Foundation

var not_a_swift_dict = [:]
print("\(_stdlib_getDemangledTypeName(not_a_swift_dict))")  //"NSDictionary"

If you want to create an empty Swift Dictionary, the proper way to do it is:

let swift_dic = [<SomeType>: <SomeType>]()

Remember from Swift arrays that declaring and instantiating a dictionary in Swift are two different processes. Unless you are using a literal, you have to declare a Swift dictionary and then instantiate it.

For example, if we declare a dictionary in Swift, but do not instantiate it, properties like “count” will not exist and will cause a compile error.

var not_instantiated_dictionary = [String: String]
not_instantiated_dictionary.count //error

Modifying a Dictionary

Obviously, hashes and dictionaries are not very useful if you can’t add/remove items to them. Luckily, Swift uses subscript syntax for adding new objects to a dictionary which is the same style of syntax as Ruby’s hash.

hash[<SomeObject>] = <SomeObject>

Here are two examples side-by-side both using Strings as the key and value type side-by-side:

ruby_refrigerator = {}
ruby_refrigerator["milk"] = "2%"

var swift_refrigerator = [String: String]()
swift_refrigerator["milk"] = "2%"

It is important to note that we are declaring the Swift dictionary as a variable. We haven’t covered the difference between constants and variables in Swift, but know that constants in Swift are immutable. In this case, that means we cannot add or remove items from them. So, we are declaring it as a variable.

You can use the Swift Dictionary method “#updateValue” instead of the subscript syntax. However, this method has an interesting side-effect. “#updateValue” will always return a Swift optional of the old value that it is updating.

We haven’t touched Optionals yet in Swift, but they are a big and complex part of Swift that we will go further in-depth on another blog post.

For now, the most important thing to remember about Swift Optionals is that they are a type that is either some value of that type or nil.

Why is this important to “#updateValue”? Well, let’s look at our milk example above. What if we substituted Swift’s subscript syntax for the updateValue method? Would it still work? Absolutely.

var swift_refrigerator = [String: String]()
swift_refrigerator.updateValue("1%", forKey: "milk") 

“#updateValue” will actually set a value for a key if no value exists. This is similar to Ruby Hash’s “#store” method.

However, “#store” and “#updateValue” return different values. Ruby’s “#store” will return the value that was just assigned. Swift’s “#updateValue” will return the original value for the key.

But what about our example? There was no original value for milk. So, shouldn’t “#updateValue” return nil? In many cases, Swift will return an Optional where nil is a possible return value.

In this case, Swift returns a String optional (written, String?). Here’s proof:

var swift_refrigerator2 = [String: String]()
let food = swift_refrigerator2.updateValue("2%", forKey: "milk")

We don’t have to specify that “food” is a String optional, because Swift is using type inference to decide the type of “food”. It already knows the return type of “#updateValue”, so we don’t have to specify it. Type inference is a powerful, but complex, feature of Swift that gives the compiled language a Ruby-like feel at times.

So, we could re-write our example above as:

var milk_optional : String? = swift_refrigerator2.updateValue("%2", forKey: "milk")

Removing a key and its value from a Swift Dictionary with “#removeValueForKey” returns a String optional as well and operates largely the same way.

var depleting_refrigerator = ["milk":"2%"]
let milkless = depleting_refrigerator.removeValueForKey("milk")

In the case that no key exists, Swift will still return an optional.

var eggless_refrigerator = ["milk":"2%"]
let hungry = eggless_refrigerator.removeValueForKey("eggs")

Iterating over a Swift Dictionary

Just like Ruby Arrays and Swift Arrays, Ruby Hashes and Swift Dictionaries are very similar in how you iterate over them.

Each data structure can use loop for iteration. In Ruby:

best_pictures = {1973 => "The Godfather", 
                 1989 => "Rain Man", 
                 1995 => "Forrest Gump"}

for year, title in best_pictures
  puts "The award for Best Picture in #{year}: #{title}"
//The award for Best Picture in 1973: The Godfather
//The award for Best Picture in 1989: Rain Man
//The award for Best Picture in 1995: Forrest Gump

In Swift, while the syntax is similar, a Swift loop over a dictionary returns a tuple, a Swift type that does not exist in Ruby. It essentially is a single type that can contain multiple types (a dream within a dream? I know. More on this later).

In this case, this allows the Swift loop to behave very similarly to the Ruby loop.

let best_pictures = [1973:"The Godfather", 
                     1989:"Rain Man", 
                     1995:"Forrest Gump"]

for (year, title) in best_pictures {
  println("The award for Best Picture in \(year): \(title)")

//The award for Best Picture in 1973: The Godfather
//The award for Best Picture in 1989: Rain Man
//The award for Best Picture in 1995: Forrest Gump

Swift .Keys and .Values

Just like Ruby, Swift provides a couple of convenient ways for getting only the keys and values of a dictionary.

In Ruby, “#keys” and “#values” are methods that both returns arrays of their respective items, like so:

roster = {:pitcher => "Justin Verlander", 
          :first_base => "Miguel Cabrera" }
positions = roster.keys //[:pitcher, :first_base]
players = roster.values //["Justin Verlander", "Miguel Cabrera"]

In Swift, they are slightly different. In Swift, .Keys and .Values are properties of a dictionary and return not arrays, but LazyBidirectionalCollections (isn’t that a mouthful)? To convert a LazyBidirectionalCollection into a Swift Array, you pass the collection into the Swift array initializer function. For example:

let roster = ["pitcher": "Justin Verlander", 
              "first base": "Miguel Cabrera"]
let positions = [String](roster.keys) 
//["pitcher","first base"]

Note: there is another, undocumented (at least by Apple), way to convert the .keys or .values collection into an array. Why this is not documented or discussed in any way is beyond me. See below.

You can also use the convenient “array” property on each of these collections to get an array of their respective values.

let roster2 = ["pitcher": "Justin Verlander", 
               "first_base": "Miguel Cabrera"]
let positions2 = roster.keys.array

Learn more about other areas of Swift from a Rubyist’s perspective.

Swift for Rubyists: Arrays

This post is the first in a series I am doing on Swift for Rubyists.

All of the examples from this post are available as a playground to download at this repo.

Update: I have corrected a mistake in this post which stated that mixed Swift arrays of Ints and Strings worked because they were inferred to be the AnyObject type. This was incorrect. This only works in cases where you have imported the “Foundation” library or if you use the type Any. My apologies. See this article for further explanation.


Swift arrays are like arrays in most modern languages including Ruby. In some cases, they share some similar characteristics. In others, they are very different. We’ll compare how Swift handles arrays vs Ruby.

Swift Array Declaration and Instantiation

Due to type-safe nature of Swift, the declaration syntax of Swift arrays to Ruby arrays is similar, but the differences are very important.


In Ruby, it couldn’t be simpler:


In Swift, there are three main ways to declare an array. In the first two ways, you must declare the types that the array will hold. Here are the first two using an example of declaring an array to hold String types.

var swift_core: [String]
var swift_core_again: Array<String>


Luckily, Swift has a third option. They are literals and they are very similar to Ruby literals. The examples I use throughout this post will be mostly be literals. The syntax is almost identical.

ruby_array = ["Matz", "Patterson"]
var swift_array = ["Lattner", "Apple"]

In the case of literals, we do not have to declare a type for the array because Swift uses type inference to infer the type of objects that it can hold.

There is one important exception for using literals that I must point-out. It’s the shorthand syntax for how Ruby declares and instantiates an array. In Ruby, the shorthand way of doing this is:

arr = []

However, if you try to do this in Swift, and you have imported Objective-C’s Foundation library, it will compile, but it actually creates an NSArray, not a Swift Array. Take a look.

import Foundation

var arr = []
print("\(_stdlib_getDemangledTypeName(arr))")  //"NSArray"

So, if you try to use the Ruby shorthand for declaring and instantiating an array, you will get very different results in Swift.

If you wanted to do the above to create a Swift Array, you would use:

var arr = [String]()

Subtle, but important. There are actually ways to convert an NSArray to a Swift Array, but we won’t cover those in this post.

Let’s step back and talk about declaration vs. instantiation in Swift. Unless you are using a literal, Swift requires you to declare a type before instantiating an array. So, you actually have two steps if you decide not to use a literal. Declaring an array in Swift does not actually instantiate it. In this example, we declare a type in Swift, but do not instantiate it, so when we go to inspect the “count” property, we get an error.

var not_instantiated_array = [String]
not_instantiated_array.count //error

We haven’t actually instantiated our array so no “count” property exists. The proper syntax to do both is:


There are many reasons why you might want to declare an array, but not instantiate it, however, we won’t cover those here. Just know that Swift treats them separately when declaring an array.

Containing Items

Maybe the biggest and most important difference between Swift arrays and Ruby arrays is what kind of items that they hold.

In Ruby, arrays can hold multiple kinds of items in one array. For example, this is a valid array in Ruby:

mixed_array = ["apple", 1, OpenStruct]

On the other hand, Swift emphasizes type-safety. Swift arrays can only hold instances of one type.

Here are some examples of valid arrays in Swift:

var fun = ["Some Nights", "We Are Young", "Carry On"]

var lions = [9, 81, 90, 21]

var name = UILabel()
var email = UITextField()

var views: [UIView] = [name, email]

Mixed arrays, such as those of Ints and Strings, can be achieved only when you have imported the “Foundation” library. For example, here’s a valid array that holds both Int and String types.

import Foundation

var inebriated_array = [99, "bottles", "of beer"]

This can be achieved because Swift is automatically converting the instances to NSStrings and NSNumber classes. Check out this article here for more information.

Type-safety also applies if you try to add an element which does not match the type of the existing elements of an already instantiated array. For example, if we try to add an element using Swift’s “#append” method, this will not compile:

var broken_up = ["Blink"]
broken_up.append(182) //compile error


Ruby and Swift are almost identical with regards to the syntax of how to add an element on to the end of an array. Here’s an example in Ruby of adding two arrays together.

a = ["Simon"]
a += ["Garfunkel"]

In Swift, it’s the same.

var band = ["Simon"]
band += ["Garfunkel"]

In Ruby, you can use “#push”, which returns the modified array so you can assign it to something else.

chocolate_shake = ["Milk", "Ice cream", "Chocolate"]
mud_slide = chocolate_shake.push("Rum")

In Swift, you can use “#append”, but the method does not return the modified array.

var chocolate_shake = ["Milk", "Ice cream", "Chocolate"]

There is no equivalent to Ruby’s popular “<<” syntax out of the box. Although, we may cover this under Custom Operators later.

isEmpty vs. Empty?

Ruby provides many useful convenience methods for finding out more information about the state of an array. For example, Ruby provides an #empty? method to check whether an array has any elements.

vending_machine= []
vending_machine.empty? => true

Swift provides a similar feature via a property called isEmpty.

var vending_machine = Int
vending_machine.isEmpty //returns true


Iterating over the elements in an array in Ruby or Swift are very similar. Like many languages, Ruby and Swift both offer a “for…in” loop. Here’s an example in Ruby.

beatles = ["John", "Paul", "George", "Ringo"]

for member in beatles 
  puts "Here's #{member}"

In Swift, the syntax is almost exactly the same.

var beatles = ["John", "Paul", "George", "Ringo"]

for member in beatles {
   println("Here's (member)")

If you need the current index of the element that you are iterating over, similar to Ruby’s “#each_with_index” method. You would use the “#emunerate” function in the loop. Each iteration of enumerate returns a tuple containing the index and the element. We’ll cover tuples another time.

var beatles = ["John", "Paul", "George", "Ringo"]

for (index, member) in emunerate(beatles) {
  println("Playing #(index)")
  println("Here's (member)")

More to Learn

This is just a brief introduction to Swift arrays for Rubyists. If you have found this information useful and would like to learn more, please sign up for the Swift newsletter below and I will send you updates when new posts and videos become available. You’ll also receive access to my video tutorial “Advanced Swift Arrays”.

Learn more about other areas of Swift from a Rubyist’s perspective.

I also highly urge you to read Apple’s official documentation on Swift.

Introducing – Swift For Rubyists

As a Ruby developer, I had been looking to pick up iOS development for a while. I was lucky enough to take a course in it in the summer of 2014. The course covered Objective-C as well as the iOS API. Then Apple released the Swift programming language during the middle of the course, and the focus switched to learning Swift.

I’ve decided to write a series of posts on Swift for Rubyists. Theses posts will be centered around what I’ve picked up as a Rubyist learning Swift and the key points to note if you are a Rubyist who is attempting to learn Swift as well. I hope these posts will be helpful for other Rubyists looking to pick up Apple’s latest programming language.

Note: While Ruby is an excellent language, these posts are not meant to be a substitute for reading the Swift documentation and utilizing Swift’s own strengths and weaknesses. Using only the parts of Swift which are familiar to Ruby would be a waste of a very powerful and robust language. These posts are meant to be guides to help Rubyists transition to learning this fascinating new language.


5 Vim Plugins that Helped Me Switch From Sublime

A month ago, I wrote a post about how I finally learned Vim. I gave a couple of simple steps that were the central focus of how I was able to switch from Sublime Text to Vim.

While these steps were the primary reason I was able to learn Vim, Vim plugins were a close second. While I had wanted to switch to Vim for a long time, I knew there would be parts of Sublime that I would miss. Little did I know the extensive power of vim plugins.

With a bit of browsing, Google-ing, and reading other developers’ dotfiles, I found a couple of plugins that would replace (at least, temporarily) certain functionality that was available in Sublime but was missing from Vim’s core. These plugins helped me slowly make the transition over to using Vim exclusively.

Here are the 5 plugins that helped me the most.

#1 Vundle

Vundle List of Vim Plugins

My Current List of Plugins

Similar to Sublime’s Package Control, the Vundle plugin is just a plugin manager (a dream within a dream?) Like many package managers today, it is inspired by Ruby’s Bundler, which is part of the reason I gravitated to it, because I’m already familiar with the Bundler model. After installing it, adding a new plugin to Vim becomes as simple as adding one line to your .vimrc file and running “:PluginInstall”

There are many plugin managers for Vim out there as well. Check out Pathogen if you would like an alternative.

#2 ctrlp

One of my favorite parts of Sublime was the fuzzy file search capability that came out of the box. In Sublime, the command to open the search is “command+p” or “command+t”. I knew missing this finder would probably destroy me when switching to Vim. Luckily, there’s a Vim plugin which duplicates this functionality. The aptly named “ctrlp”.

Like all of Vim, the ctrlp plugin is highly customizable as well, which can allow you to change the plugin to your liking. For example, I changed the primary “ctrl+p” command to always flush the cache before opening the search so that it will index any new files that I’ve added. Also, you can configure it to ignore certain file types and directories (I’m looking at you ./tmp).

#3 NerdTree

nerdtree vim plugin

Ctrlp is great when you know the file(s) that you are looking for. But what if you don’t know the name of a file that you are looking for? In Sublime, you have the slide-out folder directory which will allow you to browse and navigate a project’s structure quickly.

NerdTree is a Vim plugin which will give you the same ability. Just a quick toggle (I’ve mapped it to Space + “ne”) and you can quickly open a “NerdTree” and navigate a project structure. Of course, you can do a lot more. This plugin is immensely useful when I can’t use ctrlp.

#4 tcomment_vim

I need to quickly iterate and try new ideas when I am developing. One of my tricks to do that is to comment out a line or block of code.

In Sublime, this is fairly straightforward. However, utilizing the excellent ‘tcomment’ plugin, commenting is even quicker. This plugin maps ‘gc’ to allow you to comment out large amounts of texts quickly. For example, if I want to comment out the next five lines of code, it’s simply ‘gc4j’. Like Sublime, it will also try to automatically recognize the language of the file and apply the proper commenting syntax.

#5 The Silver Searcher

There were many times during my Sublime days when I would need to lookup and piece of code in a project. In Sublime, I would open up the project-wide ‘find-all/search-and-replace’ menu and type in what I was looking for. Sublime was usually quick to respond with where it could be found in the project.

Unfortunately, Vim does not come with current directory/project-wide search functionality out of the box, but luckily, there’s a great alternative.

The silver searcher is a *nix command line utility for replacing the search abilities of an ack or grep. And it is ridiculously fast.

Ok, I know what you are thinking…wait this is a command utility, not a Vim plugin. Correct. But, luckily some vim faithfuls have created a couple of Vim plugins which will allow you to use the silver searcher from a command in Vim. So, you can search can search an entire project without leaving Vim.

I use ag.vim. The experience is not as smooth as the command line and sometimes I have to jump out of Vim to use the full power of the silver searcher, but nonetheless, it gives me at least a close replacement to Sublime’s find-all.

Honorable Mentions

I have a few more plugins that I utilize in Vim. Some I use more than others. However, none were quite as important to my transition to Vim as the ones above.

The one exception is vim-rails, which is a MUST have Vim plugin if you are a Rails developer. However, I decided not to list it, because the rest of the plugins are language-agnostic and all developers seeking to make the transition can use them.

Here’s a few others that I use:

Vim Plugins…Good or Bad?

I’ve heard the argument that some feel that Vim plugins are too much of a crutch or that customizing Vim beyond recognition hampers your ability to pair with other programmers. These are all valid points. But the goal I had set for myself was to just switch to using Vim full-time for my development, so I wasn’t concerned with pairing or that I was using plugins as a crutch. I knew I had to learn to crawl before I could run.

Freelance Elixir & Ruby on Rails DeveloperHey, I’m Adam. I’m guessing you just read this post from somewhere on the interwebs. Hope you enjoyed it. When I’m not writing these blog posts, I’m a freelance Elixir and Ruby developer and working on Calculate, a product which makes it easier for you to create software estimates for your projects. Feel free to leave a comment if you have any questions.

You can also follow me on the Twitters at: @DeLongShot

Web Sites vs. Web Applications – What’s the Difference?

I’ve been a software developer for a while now and one of the types of software that I specialize in is web applications.

Now, I live in an area where technology is not a large segment of the local economy, so when I tell people that I meet that I build web applications, I often get the question…

“What’s the difference between a web site and a web application?”

First, Some History

To understand the relationship between these two concepts, we have to think back to 15-20 years ago. Back in the early days of the internet. Back then, the internet was still the world-wide-web made up of “sites”. To popular culture, everything on the internet was a “site”.

But one thing I’ve learned from studying pop culture (I studied film and video in college) is that once popular culture latches onto an idea, it takes a while to let go.

Fast-forward to now, the internet is full of new and innovative technology. And yet, if you wanted to know more about popular things on the internet, you would probably ask “What are some popular sites I should check out?” The term has largely stuck to mean “places”. So, in this context, we would believe that “site” is synonymous with “place”.

What Do You Need?

So, if site is synonymous with place, then why is it important to distinguish between a site and an application?

Well, with many things with technology, while this definition of “site” has stuck, internet technology has advanced far beyond this original definition. Sites are now vastly more complicated than 15 or 20 years ago. Sites exist on a spectrum of complexity ranging from relatively straightforward informational site to an interconnected series of applications like Facebook.

They also share different purposes and these purposes are what help a software developer determine where the effort used to create a site should be focused.

This becomes a problem when discussing what you need and how to “build a web site”. If we don’t share the same definition of “site”, then our conversations over how to build a your site are likely to be fraught with misunderstandings about what it actually takes. What do you need? How complex is it? Is it really a site or an application?

So, What’s the Difference?

If we go by “web sites” as defined by popular culture, then we have a problem when comparing “sites” to “applications”.

Is there a difference between a pitch and curveball?

See the problem? What we are comparing is a little bit of apples to Jonagolds. Using this definition of site, then a web application is a kind of web site. It becomes difficult to distinguish the differences between the two.

Instead, I propose that we can delineate between the two by describing the relationship that the site or application has with a visitor.

  • Web site: A place on the internet whose purpose to the visitor is to provide value through presentation of information. A site is largely a “one-way” relationship, where visitors consume content from the content creators.

  • Web application: A place on the internet that requires input from the user, aside from clicks, in order to provide substantial value to the user. An application is largely a “two-way” relationship, where visitors must interact either with each other or with the application or both.

Ok, we’ve defined the difference. But maybe the definition is still a little unclear. How about some examples?

But are there places that fall into both categories? Let’s look at the Waste Management site as an example. Could this qualify as both? It certainly could. Why?

  • The homepage definitely is a one-way relationship where Waste Management is providing the visitor information about their good and services.

  • However, you can see the visitor has the ability to pay their bill online. This would qualify as a web application, because the visitor will surely be required to provide some information to the bill pay application in order for it to be of any value.

What do we call this? A site? An application? In the case of Waste Management’s homepage, many technology professionals are starting to call this the “marketing site” in order to differentiate it from the online bill pay, which is considered an application. But of course, in order to provide a good visitor experience, they are all tied together.

So, you can see that even with these definitions, some sites may fall into both definitions, but that we can clearly define where a difference in behavior exists. My definitions are by no means meant to be dogma, but I hope they help the discussion of what it takes to build a web site or web application.

Testing That Elements Do Not Exist With Capybara

I came across a problem that I’ve had with Capybara testing that has come up for me before.

In my test, I needed to check that an element was not on screen. I was trying to use Capybara’s #find method combined with RSpec exist matchers to keep the tests fast.

admin_section = find("#admin")
expect(admin_section).not_to be_present

However, you can’t use Capybara’s #find method here in this case, because it will throw an error (ironically, that it can’t find the element, thus, returning nil) before the matcher can be evaluated. Capybara will also wait 2 seconds before finally throwing the error which will actually slow down the test.

I Googled for the answer and while this Stack Overflow answer does provide the basic answer, it doesn’t use the new “expect” syntax. Here is how to check that an element does not exist on-screen using the expect syntax.

expect(page).not_to have_selector("#admin")

I don’t test much for elements that are not on-screen. But, for certain, exceptional cases, I will test when I want to make sure that an element is not appearing on-screen (say, a link to the admin section when you are a typical user).

However, I rarely test solely that an element does not exist on screen. The reason for this is that there are too many ways that an element could not appear on-screen. For example, maybe normally a test needs to be logged-in for the scenario under test but for some reason, my tests are logging out early. Now, my “not present” test may still pass because the element still does not exist on-screen but that’s because I’m logged out.

To account for this, I usually include an assertion for a similar element nearby that should be visible and is related in behavior to the element that is supposed to be hidden.

expect(page).to have_selector("#profile-photo")
expect(page).not_to have_selector("#admin")

If you are curious, ThoughtBot’s Joe Ferris hits on the points about using RSpec matchers like “have_selector” over Capybara’s #find method in this post on asynchronous testing.

Adam DeLong - Freelance Ruby on Rails Developer Hey, I’m Adam. I’m guessing you just read this post from somewhere on the interwebs. Hope you enjoyed it. When I’m not writing these blog posts, I’m a freelance Elixir and Ruby developer and working on Calculate, a product which makes it easier for you to create software estimates for your projects. Feel free to leave a comment if you have any questions.

You can also follow me on the Twitters at: @DeLongShot