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"}
//or
{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")
print("\(_stdlib_getDemangledTypeName(food))") 
//Swift.Optional

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")
print("\(_stdlib_getDemangledTypeName(milkless))") 
//Swift.Optional

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

var eggless_refrigerator = ["milk":"2%"]
let hungry = eggless_refrigerator.removeValueForKey("eggs")
print("\(_stdlib_getDemangledTypeName(hungry))") 
//Swift.Optional

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 for..in 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}"
end
//Outputs
//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 for..in 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 for..in loop to behave very similarly to the Ruby for..in 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)")
}

//Outputs
//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

More to Come

While we covered a bit about Swift Dictionaries for Rubyists, this post has only been a brief introduction. If you have found this information useful and would like to learn more, please sign up for my Swift Newsletter below and I will send you updates when new posts 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.

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.

Arrays

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.

Declarations

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>

Literals

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:

[<SomeType>]()

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

Appending

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"]
chocolate_shake.append("Rum")
print(chocolate_shake)

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

Iteration

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}"
end

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 for..in 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.

Enjoy.

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.


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

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?
waste_management_homepage

  • 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.


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

Setting Up Multiple Instances of MongoDB on OSX

This post was originally published in February 2013 on my old blog. Some of this information may no longer work. I am posting this just as a reference for those curious as to how I did this originally back in 2013. For more up-to-date information, I would check the MongoDB site or Google.

I ran into an interesting problem the other day. I was working on a problem that required MongoDB’s new aggregation framework that comes standard with MongoDB ~> 2.2. However, I already had a local version of MongoDB v2.0 installed on my mac via Homebrew which I was using to test and development a production database that we were running. Searching the web, I found very little information about how to setup multiple versions of MongoDB on the same local environment.

So, here are the steps I used for setting up a separate instance of MongoDB. Again, I had already installed MongoDB via Homebrew using brew install mongodb, so I’ll show you how to install your own version outside of homebrew.

First, you’ll need to download a version of MongoDB from their website. In this case, we’ll use the latest production release which is 2.2.2 at the time of this post. In addition, I will be using the 64-bit OSX version from their site.

Then create an empty directory wherever you would like MongoDB to live. I call it mongo2_2 here but you can call it whatever you would like:

mkdir mongo2_2

Then you need to untar the download into that directory. In this case it’s:

tar –zxvf ../mongodb-osx-x86_64-2.2.2.tgz

This should create a new directory mongodb-osx-x86_64-2.2.2. ‘cd’ into that directory and you will see that it has created a “bin” folder with all the MongoDB commands and executables. Some of these you may recognize, like the actual MongoDB process – mongod and the mongo shell, mongo.

Ok, you have mongo setup, but now you need a place to store the data. By default, mongod writes data to the /data/db/ directory.  However, if you have installed MongoDB via Homebrew, then mongo is configured to write to /usr/local/var/mongodb

For the ease of use, we’re just going to use the directory we are currently in. We’ll create a “data” directory in the current directory which should be something like:

~/mongo2_2/mongodb-osx-x86_64-2.2.2

Run:

mkdir data

Ok, now you should be all setup for a new instance of MongoDB. But first, before we fire that up, there are a couple of things to check first. If you installed MongoDB via Homebrew, then more than likely, MongoDB is running on startup. You can check if this just by running the mongo shell with the “mongo” command:

Mongo

If an instance of mongod process is running, then it should have no problem connecting. It might give you a message like

MongoDB shell version: 2.0.x

Uh-oh, not what we wanted. This means that your other version of MongoDB is still running and you need to stop it before you can start up the new version. To double-check this run:

ps -ef | grep mongo

If mongo is running, you should see mongod in your list.

usr/local/bin/mongod run --config /usr/local/etc/mongod.conf

To triple-check this, MongoDB runs off port 27017 by default, you can go to localhost:27017 and you should see a message like this:

You are trying to access MongoDB on the native driver port. For http diagnostic access, add 1000 to the port number

You can cancel a mongod process by running the mongo shell with the “mongo” command then issuing the following commands in the shell:

use admin 
db.shutdownServer()

You could try to just kill the mongod process in the terminal, but there are no guarantees about how that might affect your current MongoDB setup and database. I preferred the safe route this time.

Ok, now if you try to connect to MongoDB again using the mongo command. You should get an error:

Error: couldn't connect to server 

Good, now we know that process is gone. However, if you plan to use this setup more than once, I would recommend one more change. The homebrew version of MongoDB is still setup to start automatically on startup. To turn this off, you need to edit a LaunchAgent file that Homebrew sets up by default. First, cd into the LaunchAgent directory

cd ~/Library/LaunchAgents

You should see a file called homebrew.mxcl.mongodb.plist. Open up this file in your favorite file editing software and change the following line:

RunAtLoad

to:

RunAtLoad

The next time you start up again, MongoDB will not start by default.

We just need to set the configurations for our new MongoDB instance and then we should be good to go. ‘cd’ back into the directory where you setup MongoDB.

~/mongo2_2/mongodb-osx-x86_64-2.2.2

In order to tell MongoDB your settings when you start a mongod process, you will need to setup a config file. Create a new mongod.conf in this directory and include the following code:

# Store data in ./my_data instead of the default /data/db
dbpath = ./data
port = 28028

# Only accept local connections
bind_ip = 127.0.0.1% 

dbpath tells mongo where you data should be stored, in this case, the data directory we created earlier. Port sets the port where the mongod instance should run. You’ll have to set this to something other than the default 27017 or mongo will complain. Bind_ip is important and prevents outsiders from trying to connect to your db.

You can now start your new instance of mongodb. However, you can’t use the “mongod” command, this is pointing to the executable of your homebrew version. ‘cd’ into the mongodb-osx-x86_64-2.2.2 and run:

./bin/mongod --config mongod.conf

This will tell the terminal to look for the mongod executable in the current directory and to use your config file for setup. You should see a message like:

MongoDB starting : port=29029 dbpath=./data

Woo-hoo! Alright, now you can connect via the shell to make sure. Open a new terminal tab. You’ll need to run the “mongo” command from the ./bin directory like we did with mongod. You will also have to specify the port or the shell will try to connect to the default port and throw and an error. Run this command

./bin/mongo –port 28028

You should see something like this:

MongoDB shell version: 2.2.2
connecting to: 127.0.0.1:29029/test

Success! Now you are free to play with a different version of MongoDB all you want without having to touch your current setup. When you are done, just remove the mongo2_2 directory and change the LaunchAgent back and you are all set!