Our Blog
Where we share our latest stories
Sep
24
A Case for Using Procs BY localflavor

I’ve read about and practiced working with Ruby procs — all with contrived examples. That’s all well and good, but for me, the best learning comes with a heaping helping of context, which has been sorely missing from most of the contrived examples. I finally got some good context today when the need for a proc sprung up organically in a code challenge I was working on. So now I get it. I have a much stronger foothold on procs and when to use them. Hopefully seeing my process here will help build context for when you may be able to use a proc to solve a similar problem.

The Challenge: Building a Message Cipher

Here’s the challenge: I’m building a message cipher — a small program that will encode and decode messages. The cipher is very basic. When it encodes, it takes a letter and simply moves down the alphabet the number of letters provided by the given offset. For example:

    0 1 2 3 4 5 6 7 8 9 ...
    a b c d e f g h i j ...

    offset = 3
    input a --> output d
    input c --> output f

Here’s my original encode method. For the sake of simplicity in explaining procs, this encoder does not handle wrapping the alphabet for letters exceeding “z”.

    def encode(message, offset, adjusted_index_proc)
      output = []
      message.chars.each do |letter|
        new_index = ALPHABET.index(letter) + offset
        output << ALPHABET[new_index] end output.join() end # Outputting the results: cipher = Cipher.new p cipher.encode('ilikekitties', 3) > lolnhnlwwlhv

After writing the encoder, I realized that the only difference between the process of encoding and decoding was the use of + or -. Instead of creating a nearly identical decode method, I decided to extract the encode/decode logic out into their own methods and leave the rest of the process in a method called processor.

  def processor(message, offset, adjusted_index_proc)
    output = []
    message.chars.each do |letter|
      #
      # This part will need to become generic
      # so it can both encode and decode.
      #
    end
    output.join()
  end

  def encode(message, offset)
    #
    # Encoding-specific code will go here,
    # then we'll call the processor method.
    #
  end

  def decode(message, offset)
    #
    # Decoding-specific code will go here,
    # then we'll call the processor method.
    #
  end

Then I realized that in order for the encode/decode methods to work, they’ll have to access the value of the letter iterator happening in the message.chars.each do |letter|... block inside the processor method. Yikes. So how do you do that?

Procs! Tada! I found my own completely non-contrived use for a proc. At last. Here’s how it plays out:

Incorporating the proc logic

I created a new proc for both the encode and decode methods:

  def encode(message, offset)
    proc = Proc.new #...
    processor(message, offset, proc)
  end

  def decode(message, offset)
    proc = Proc.new #...
    processor(message, offset, proc)
  end

And then passed the proc into the processor method as an argument.

  def processor(message, offset, adjusted_index_proc)
    # ...
  end

I needed the proc inside the each loop to:

  1. take the value of the current message input letter
  2. get the index of where it is stored in the ALPHABET array
  3. add the offset value (3) to that index
  4. return the new index number for the encoded letter

So the encode and decode methods with their procs look like this:

  def encode(message, offset)
    proc = Proc.new { |letter| ALPHABET.index(letter) + offset }
    processor(message, offset, proc)
  end

  def decode(message, offset)
    proc = Proc.new { |letter| ALPHABET.index(letter) - offset }
    processor(message, offset, proc)
  end

The new processor method takes the proc and .call()s it along with a letter argument for each letter of the input message inside the each loop. That new index is then used to get the value of the new letter from the ALPHABET array and then the new letter is pushed into the output array.

  def processor(message, offset, adjusted_index_proc)
    output = []
    message.chars.each do |letter|
      new_index = adjusted_index_proc.call(letter)
      output << ALPHABET[new_index]
    end
    output.join()
  end

Lastly, the output array is joined back into a string and we get our encoded/decoded message.

  # Outputting the results

  cipher = Cipher.new

  p cipher.encode('ilikekitties', 3)
  > lolnhnlwwlhv

  p cipher.decode('lolnhnlwwlhv', 3)
  > ilikekitties

Though this is not the most streamlined or elegant cipher code base, it has been useful to me in building my understanding of procs. I hope it’s been useful to you too!

Sep
22
Finding prime numbers in Ruby BY localflavor

Code quizzes commonly have a prime number challenge, which got me to thinking, shouldn’t there already be an is_prime method? Well, yes, there should be. And in Ruby, there is.

Ruby has a Prime class and it does some useful things for you when you require 'prime' in your file. Two of my favorites are:

Return true if a given number is prime

require 'prime'

Prime.prime?(8753)
#=> true

Prime.prime?(4)
#=> false

Awwwwww yeah! That’s the stuff right there.

Generate a list of primes starting with 2 through a given number

require 'prime'

Prime.each(27) do |prime|
  p prime
end

#=> 2, 3, 5, 7, 11, 13, 17, 19, 23

Those two methods alone have pretty much handled any prime number code challenge that’s comes my way. If the challenge is about researching a programming language to see what options are available, this approach wins — hooray!– because learning a language’s libraries and methods makes us stronger, faster, and more efficient. Ah yes, proficiency leads to efficiency… I like that.

Creating our own is_prime method

But let’s be honest, code challenges involving math are usually focused on manipulating the basics of a language to solve a math problem, not about accessing the libraries or gems you’d probably use in real life. Code challenges like to make you do logic calisthenics, so let’s do this thing the hard way.

Here’s some pseudocode for my approach:

  • Create a range of numbers from 2 to one less than the number in question (num - 1)
  • Loop through that range
    • Ask if the number in question (num) is cleanly divisible by each number in the range (n)
    • If any one of those range numbers (n) creates a 0 remainder when the number in question (num) is divided by that number (n), the number in question (num) is not prime
  • If at the end of the loop, none of the range numbers (n) created a 0 remainder, the number in question (num) is, indeed, prime

And now for the actual code:
Using the Ruby each loop:

def is_prime(num)
  (2..(num - 1)).each do |n|
    return false if num % n == 0
  end
  true
end

is_prime(7)
#=> true

is_prime(4)
#=> false

Using a Ruby while loop:

def is_prime(num)
  n = 2
  while n < num
    return false if num % n == 0
    n += 1
  end
  true
end

is_prime(7)
#=> true

is_prime(4)
#=> false

The Ruby while loop approach might feel familiar to people coming to Ruby from JavaScript because its iteration is transparent like JavaScript’s for loop. After all, there’s none of that kludgy (2..(num - 1)) to define the iteration range like there is in the Ruby each loop. For good measure, here is a JavaScript version of isPrime.

Using the JavaScript for loop:

function isPrime(num){
  for (n = 2; n < num; n++) {
    if (num % n == 0) return false;
  }
  return true;
}

isPrime(7);
//=> true

isPrime(4);
//=> false
Sep
16
Output to Ruby hashes in one step with each_with_object BY localflavor

Today I discovered Ruby’s each_with_object method and I thought it was pretty nifty. Here is how it works.

An example with an output array of doubled values:

nums = [1, 2, 3, 4, 5]

nums.each_with_object([]) do |num, output|
  output < < (num * 2)
end

#=> [2, 4, 6, 8, 10]

You may say, “meh, this works one heck of a lot like map but clunkier.” And you’d be right.

nums = [1, 2, 3, 4, 5]

nums.map do |num|
  num * 2
end

#=> [2, 4, 6, 8, 10]

But if you want to output a hash, you may start to see its value. Here we’ll output a hash that counts instances of a letter in an array:

letters = %w[a a a b c c d e e e f f f f g g]

letters.each_with_object({}) do |letter, output|
  output[letter] ? output[letter] += 1 : output[letter] = 1
end

#=> {"a"=>3, "b"=>1, "c"=>2, "d"=>1, "e"=>3, "f"=>4, "g"=>2}

Now that’s pretty nifty.

The other option is to use plain each, hoist the output variable in advance, and then return it. Like this:

output = {}

letters.each do |letter|
  output[letter] ? output[letter] += 1 : output[letter] = 1
end

output

#=> {"a"=>3, "b"=>1, "c"=>2, "d"=>1, "e"=>3, "f"=>4, "g"=>2}

But this ain’t JavaScript, so why hoist if you don’t have to? ;)

If you’d like a few more examples, check out this post by Agnieszka Matysek of womanonrails.com.

Jul
14
How to make ruby shortcuts (snippets) in Sublime Text BY localflavor

Typing Ruby erb tags is a past time pursued intentionally by… no one. The characters <%= %> don’t exactly flow off the fingertips. So how do people get around typing these irritating-but-crucial characters?

Why, SublimeText snippets, of course! SublimeText 3 is a popular text editor among rubyists and it has a lot of great features. One of my favorites is snippets.

What is a snippet?

A snippet is a keystroke shortcut you create that will generate text for you. There are some built-in snippets in Sublime that make my life easier. For example, if you type lorem + TAB you’ll get a short paragraph of lorem ipsum placeholder text.

So how do we get to automate those pesky erb tags? By making our own custom snippets.

In SublimeText 3, go to Tools/Developer/New Snippet

open a new snippet template

You’ll get a snippet template that looks like this:

It looks a little crazy, but don’t panic. It’s all really useful stuff and I’ll get to that in a bit. First, let’s cut to the chase and make those erb tags.

The TLDR:

Assuming you want your shortcut word to be puts, delete everything in that file and replace it with this:

Save the file as erb-puts.sublime-snippet.

Now, when you’re inside an erb file like index.html.erb, you can simply type your new shortcut + TAB and you get your erb tags. Hooray!

What it’s doing and how to customize:

The content tags house the end result of the snippet. The ${1} is where your cursor will end up after you hit TAB.

The tabTrigger tags hold the shortcut word you’ll use before triggering the shortcut with the TAB key

The description tags are optional and display more meaning if you have several similar snippets. This one is super gnarly because it is using code to literally display the characters <%= %>. You could simply type “erb tag” and be done with it.

The scope tags are also optional and limit the snippet to running in only the types of files you designate here. This scope limits this snippet to work in erb files only. If you want your snippet to work in all file types, delete this line.

Here’s an excellent gist with a list of scopes for SublimeText 2, most of which work in SublimeText 3 as well.

 

Building a more complex snippet

So let’s build a new snippet. Here’s one I use a lot:

This is the core snippet code. It will generate a blank snippet:

Much like the myriad of country songs based on this poem, it’s that space between those brackets that’s important — but a lot less cheesy. This is is between the brackets for this specific snippet:

The ${1} is the first tab-stop placeholder. This means that after I type my trigger of a plus the TAB key, all of that html shows up and my cursor is placed in the 1st placeholder inside href="". Now I can type or paste a URL:

When I hit the TAB key again, it moves to the second placeholder, ${2:_blank}, which is inside the target="". This placeholder is special because I gave it a default value of _blank. I could simply start typing to replace that default value with something else.

But I like it as _blank, so I just hit the TAB key again and move on to the next placeholder.

The third placeholder, ${3}, is also special because there are two of them: one in the alt="" and one in the title="". My cursor will actually be in both of those spaces at the same time, so whatever I type will show up in both of those places.

Kaboom! right? This discovery opened up my world of snippet-making.

Now, hit the TAB key again, and we’re in placeholder #4. Nothing special here. I can fill it out, hit TAB again and my cursor will move to the first space outside of the snippet.

So hopefully this gets you started on a path to using SublimeText more efficiently so you can spend less time typing and more time coding. Though you’ll start to discover your snippet needs pretty easily on your own. Here are some ideas:

  • get binding.pry with pry
  • commenting your closing divs with the name of the class you’ve assigned them
  • commenting your closing ruby method ends or closing javascript braces
  • building our your initialize(args) like @name = args[:name]s

Also, just in case you want to reference a snippet you’ve already made, check out this post I recently wrote about how to easily access your existing snippets.

 

Jul
14
How to Access Your Sublime Snippets BY localflavor

Once I discovered the power of SublimeText’s snippet feature, there was no turning back. Any time I find myself typing a thing that could be automated, I make a snippet for it. The trouble is, sometimes I like to look back at my existing snippets, but I couldn’t get to them easily. Well, I’ve solved that problem today and figured I’d share it with you. Here is how to easily access your existing Sublime snippets on a mac.

1. Create an alias called snippets in your .bash_profile
In terminal, open your .bash_profile file in your default text editor

# if sublime is set as your default text editor
open ~/.bash_profile  

# if you use the subl shortcut   
subl ~/.bash_profile     

2. Add one of these aliases to the bottom of your file (or next to any other aliases you may have)

# for SublimeText 3 
alias snippets='cd ~/Library/Application\ Support/Sublime\ Text\ 3/Packages/User ; ls'

# for SublimeText 2
alias snippets='cd ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/User ; ls'

4. Save the .bash_profile file

5. Restart terminal

6. Try it out!
Type your new alias at your command prompt

snippets

This will open the snippets directory and show a list of all existing snippets. From here, you can open any of those snippet files in your default text editor with:

open file_name_goes_here

or if you prefer to open the snippets folder in Finder window, you can open a finder window like this:

cd ../; open User

That’s it! This discovery has really made my day. I hope it’s helpful to you too.

If you need a refresher on how to create your own sublime snippets, check out this post I recently wrote on the topic.

Jul
12
Using variables in CSS BY localflavor

If you find yourself working in CSS and missing the ability to use SASS variables, oh boy do I have a treat for you. You can use variables in CSS. They just look a little bit different than they do in SASS.

Set them up in a root block at the top of your stylesheet:

:root {
  --brand-color: #2C9C20;
  --secondary-color: #317BE1;
  --fave-size: 50px;
}

And use them in a class with a var():


:root {
  --brand-color: #2C9C20;
  --secondary-color: #317BE1;
  --fave-size: 50px;
}

.awesome-class {
    background-color: var(--brand-color);
    height: var(--fave-size);
}

They even work inside the CSS calc() function:

.awesome-class {
    ...
    margin-bottom: calc(var(--height) * 2);
}

Hooray! This discovery really made my day.

Jun
22
Using Git is like Sending Packages in the Mail BY localflavor

So you’ve just gotten your feet wet with web development or programming and in the whirlwind of setting up your machine for class, you have a GitHub account and Git installed on your machine. The trouble is, though you understand that Git is version-control software, you still don’t really understand the whole staging and committing process. What’s the differences between git add and git commit?

Git is very feature rich, so there is plenty to learn. But to help you wrap your head around the basics, think about the Git process of saving and sharing files like packing a box full of gifts to ship off to your mom. So let’s start there.

Part 1: The process of shipping a box of gifts to your mom

So you’ve been gathering a bunch of gifts to send to your mom. What things do you need in order to make that happen?

  • Your pile of gifts
    • your favorite pair of pants that you need her to repair
    • the fragile family heirloom you’ve been meaning to return to her
    • an iPad
  • A box for shipping
  • Some tape
  • Your mom’s shipping address
  • A postal service

Now let’s walk through the steps we take to make it happen:

  1. Place each gift into the box
  2. Close the box and tape it up, including a little note for your mom
  3. Affix your mom’s address on it
  4. Set the package on your front porch, assuming the postal service will pick it up when they make their rounds (we’re pretending that the postage is free)

Hooray! Now you know how Git works.

Part 2: The process of pushing your code to GitHub

Okay, so that wasn’t too helpful. So here’s the process again with Git-speak:

1. You’ve been gathering gifts (or doing work on files: pants.html, heirloom.html, and ipad.html) on a branch you’re calling gifts_for_moms_house

2. Place each gift (or each file you’re ready to send) into the box one at a time or all at once. Once everything’s in the box, we say all of your files are in “staging.”

  git add heirloom.html    # for one-at-a-time
  - or -
  git add .                # for all files at once

3. Close the box and tape it up, including a little note for your mom. Now your files will be “committed” in a single “commit” (or box) with a commit message.

git commit -m "gifts for mom"

4. Set the package on your front porch, assuming the postal service will pick it up

git push

5. The postal worker tells you your box is missing an address and suggests one based on the branch you’re on: origin gifts_for_moms_house

6. Affix your mom’s address (a.k.a. branch name) on it and hand the box back to the postal worker, who then delivers the package

git push --set-upstream origin gifts_for_moms_house

Ahh, it is starting to make sense? Now the thing I didn’t really understand when I was first learning this was why in the heck we bother with the two steps of adding AND committing? Can’t that be just one step? Sure, you can set up your git that way. But I don’t recommend it and this is why: You’re going to make mistakes. You’re going to make lots of mistakes all over the place and at every step of the process. I do. Everyone does.

Handling Mistakes

So let’s start over. You’re happily adding gifts to the box for your mom and have just added the last one. Now that you’re looking at that fragile heirloom sitting in the box (in staging), it occurs to you that you maybe should have wrapped it in something protective before putting it in the box. Whoops! Now you need to take it out of the box, wrap it up, and then put it back in the box. Good thing you haven’t sealed up that box (committed) yet!

Removing a file from staging (getting that heirloom back out of the box)

Take the heirloom file out of staging (out of the box) while leaving the others in place:

git reset heirloom.html

After we wrap it up securely, we can add it back to the box with:

git add heirloom.html

Phew! Okay, surely we’re ready to commit now, so we do:

git commit -m "gifts for mom"

Super! The box is all taped up and ready to set out on the front porch… but you know, it sure would be nice of you if you spent a little time setting up and charging that iPad for your mom so all she has to do is turn it on. Oh crap. How do we get that iPad back out of the taped-up box?

Undoing a commit, fixing the problem, and redoing the commit (untaping that box, adding the set-up iPad, and taping the box back up)

Have no fear! Git can do that. First, take the tape off and take the gifts back out of the box. Even though it looks a little scary, this will not undo any of the changes you’ve made to those files, it will just un-package them from the commit and take them out of staging:

git reset HEAD~

Spend as much time as you’d like setting up the iPad (fixing that file you messed up royally), then add all of the gifts (all of the files) back into the box again:

git add .

And the great news is, we have reusable tape! To seal the commit back up with the original commit message and to leave a clean history:

git commit -c ORIG_HEAD

Awesome! Now you can set your box out on the front porch (push your files). So now, how does your mom actually get those lovely gifts?

Part 3: The process of pulling code down from GitHub

GitHub is like a huge digital post office in the cloud, which is organized by repositories (a.k.a. repos). When you’re working on projects with other people, you will set up a repository for that specific project and everyone on the team will have access to it. In this case, let’s say your whole family works on a project repo called family_gifts and within that repo, you have several branches. The branch you’ve seen already is called gifts_for_moms_house. You’ve told your mom that gifts are waiting for her in that branch and that she needs to request delivery of them. Okay, so we’re losing the metaphor a bit, but now this is what your mom will do:

1. Makes sure she’s inside the family_gifts directory on her command line.

2. Gets a list of all branches that exist in the family’s GitHub repo

git fetch

3. Sees that gifts_for_moms_house is there, like you said it was, and checks it out on her machine:

git checkout gifts_for_moms_house

4. Requests delivery of those files:

git pull

And that’s it! She now has the files you sent to her. If only we could actually send fragile heirlooms this way.

Understanding Git is a big learning curve for a lot of new developers, so if you have any suggestions on how to make this explanation easier to understand, please drop me a line!

Feb
08
Coming Soon: Coloring book! BY localflavor

UPDATE! It’s here! It’s here!

A is for Adventures in Adulting: An Adult Coloring Book has been published and is available to buy at Amazon, Barnes and Noble, and other fine retailers.


And now back to the original post…

Waaay back in 2010, I was interested in rekindling the idea of play for adults. So many of us find ourselves being so serious all the time, it’s kind of a drag! Those of us who do creative work know that without playfulness, there will be no creativity in our work! I thought to myself, ‘jee… I like coloring. I wonder if other adults would like to color too.” Well, suffice it to say, I was right. By 2015, adult coloring books dominated Amazon’s top selling book list.

Now comes the part where I cry a little.

I decided in 2011 that I’d create a coloring book with an animal theme — it would be called A is for An Ant on an Airplane and it would be an alliterative alphabet of animals doing adult chores. I started some illustrations for it in 2011 while I was living in Costa Rica. Here’s one from back then: T is for Turtle paying Taxes

I worked on the book off and on while we traveled between the US and several countries in Central America. To be honest, I was quite busy with client work and the adventures of traveling (like the time Mike and I chased pigs out of the back yard wearing only our underwear or the time Mike was pooped on by a howler monkey while we both struggled to have some sort of control of the horses we were riding).

By the end of 2013, we were taking a 3-month break in Panama and I was putting the final touches on the cover artwork. And then it happened. Through a glitch in my file backup system, I ended up deleting all of my book files.

Nooooooo!

Mistakes happen, and this one was painful. Instead of trying to recreate everything I just lost, I decided to let myself cry for an hour or so and then let it go. So I did. And I wrote a book about how to pack for indefinite overseas travel instead.

Now comes the part where I dance a little.

Flash forward to present day when I recovered several of these illustrations on a backup hard drive. Hooray! I’ve been working on completing the illustrations and plan to publish this spring. I’m really excited about publishing another book and this one is going to be a fun one to share! This is a screenshot of the InDesign file of my latest illustration: C is for a Caterpillar Cleaning out the Closet

Spring is coming soon, so sharpen your colored pencils and stay tuned! If you’d like to be notified, drop me your email here:

Get Notified!

 

Jan
20
Hot of the Presses: Self-Reading Tarot Deck BY localflavor

I’m excited to announce a new project I’ve been working on: self-reading Pocket Tarot decks. Lots of people are curious about tarot, but are a little hesitant to get a reading or are not willing to put in the time it takes to learn all of the cards’ meanings. About six months ago, I could certainly count myself as one. Since then, I’ve done a lot of research and created two solutions:

1. An app that does readings for me (check out ModernMystic)
2. A deck of cards with the meanings on them along with easy guides on how to interpret them

The mini size deck: https://www.thegamecrafter.com/games/nola-pocket-tarot-mini-deck
The poker card size deck: https://www.thegamecrafter.com/games/nola-pocket-tarot-poker-size

As a design project, it’s been really fun. Like a lot of products and businesses in the New Orleans area, I’ve chosen to use a customized version of the watermeter covers as a the main design.

It was also interesting to go from a full print-ready logo to one that is simplified enough to look good in embroidery stitches.

I always think it’s fun to publish something and be able to hold it in my hands. This project, however, is even more fun because of the joy it’s bringing to other people. I’ve shown several people how to use the decks and we’ve all gotten a kick out of how crazy true these readings have been.

I never thought I’d be publishing tarot decks, but hey, life is hard to predict… maybe I should consult the cards to see what’s next!

1 2 3 7