Greg Eng

An Open Code Journal

Make Your Website More Accessible With These 5 Tips

Optimizing a website to adhere to web accessibility standards allows for a wider audience and user base. An accessible website should allow users who use screen readers and/or depend fully on the keyboard to use every piece of functionality on the website, in a logical manner.

In a recent project for work, I was tasked with creating a web accessible media display that passed AA standards. The following information and tips are things I wish I had a few weeks ago in order to help with the process. I hope it helps someone else in the future!

Essentials:

  • Make sure everything is accessible by tab / shift+tab.
  • Err on the side of semantic html rather than forcing the use of the global tab index attribute. (In some cases, it will be unavoidable … like in certain description overlays or media lightboxes)
  • Provide a title to all <a> tags so that screen readers can read it.
  • Provide alt text to all images.
  • Use text as often as possible so that screen readers will successfully be able to provide voice over to the content. If it is not possible to use text due to specific styling concerns, make sure to be diligent about the alternate text that is associated with the image.
  • Choose colors with a high amount of contrast to make text easily readable.

5 Pro-Tips:

    1. Set up an event listener to add a class to the body of using-keyboard.

    This allows you to implement different :focus pseudo-class selectors when using/not using the keyboard.

    1
    2
    3
    4
    5
    6
    7
    
    $(document).keydown(function(e) {
      $('body').addClass('using-keyboard');
    });
    
    $(document).mouseup(function(e) {
      $('body').removeClass('using-keyboard');
    });
    
    2. Write :focus and :active styles.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    * body.using-keyboard:focus {
      outline: 2px dashed red;
    }
    
    *:focus {
      outline: 2px dashed red;
    }
    
    *:active {
      outline: none;
    }
    
    3. Use this function to make things behind an overlay inaccessible via keyboard.
    1
    2
    3
    
    $('.the-last-element-you-want-to-tab').blur(function(){
      $('.the-first-element-you-want-to-tab').focus();
    });
    

    Thank you to this post on stackoverflow for helping me solve this issue.

    4. Force a specific tabindex keyboard interaction flow

    If tab indexes aren’t working properly… which can be highly likely in Internet Explorer, you can force the route you want the user flow to go with this function. Note you will need to be very specific about the global tab index property.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    var tabindex = $('*:focus').attr('tabindex');
    var lastTabindex = 10;  // make this the highest tab index number you have on the page
    $(document).keyup(function(e) {
      if (e.which === 9 && tabindex !== lastTabindex) {
        tabindex += 1;
        $('[tabindex=' + tabindex + ']').focus();
      } else {
        tabindex = 1;
        $('[tabindex=1]').focus();
      }
    });
    
    5. Reset focus to triggering elements. This is applicable after visiting another page, overlay, lightbox, etc.

    An easy way to do this is to assign an id to the tag that triggers the page, overlay, or lightbox. After closing that region, reset focus to the triggering element with jQuery by focusing on the asset matching the id.

Additional Resources:

And if you were curious to interact with the final product, web accessible and all … you can check it out at:

firstdayofschool.target.com


Environment Setup for Calabash Testing

In order to begin writing automated test suites with calabash, you will need to set up your dev environment.

This is an exciting and necessary step in achieving a productive scripting work flow. So I thought I would write this guide to lower the barrier to entry and help you get up and running sooner.

Both calabash-ios and calabash-android were originially written as Ruby libraries. Therefore, I will be showing you how to set it up using Ruby and Mac OSX.

Let’s get started:

  1. Install Homebrew (The missing package manager for OS X)

    • From the shell run:

      • ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

  2. Install RVM (Ruby Version Manager)

    • Currently, I am using the following version: ruby 2.0.0p247

    • In order to replicate my environment, run this from the shell:

      • rvm install 2.0.0-p247
      • rvm --default use 2.0.0-p247

  3. Install Xcode, the Command Line Tools, and iOS Simulators

    • Open up the Mac App Store and search for Xcode.

    • Install Xcode from there and login using your Apple Developer login/password.

    • Once the application is installed, open it up and download the Command Line Tools and iOS Simulators.

      • They should be located within Xcode Preferences –> Downloads

        • If for some reason they are not available there, search for them here.

  4. Install Required Gems (The Ruby Package Management System)

    • From the shell run:

      • gem install 'bundler'
      • gem install 'calabash-cucumber'
      • gem install 'calabash-android'
      • gem install 'pry'

  5. Install the Android Debug Bridge (adb)

    • Download the Android SDK

    • Unzip the file and rename the folder to “ android-sdk

    • Nest the folder in any directory you like. I suggest /Users/YOURUSERNAME/Development

    • Add the folder location to your $PATH

      • From the shell: cd then open -a TextEdit .bash_profile

      • Add this: export PATH="/Users/YOURUSERNAME/Development/android-sdk/platform-tools/":$PATH

    • Open a new shell window and enter the command adb

    • If you see a list of adb help commands, you’re all set!

  6. Generate an Android debug.keystore

    • If debug.keystore is missing, it be recreated in ANDROID_HOME with the following command:

      keytool -genkey -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -keysize 2048 -validity 10000 -dname "CN=Android Debug,O=Android,C=US"

  7. Download Genymotion

    • This is an alternative Android emulator.

  8. Download Oracle VirtualBox

    • This works in conjunction with Genymotion to simulate Android devices.

  9. Enable the Google Playstore on all your virtual device simulators

    • If you are not signed in with an account on the Google Playstore on each device, you will not be able to run calabash automated scripts in the simulator.

    • Here is an excellent guide from Stack Overflow detailing how to do this.

    • I consistently use the Galaxy Nexus 4.3 API 18 when authoring scripts locally. Of course, feel free to choose any device or version level you want.

…and that’s it!
Assuming everything went well, you are now ready to begin writing calabash powered, automated test suites. Enjoy!


Hello Again

It’s been a few months since I’ve updated my blog and I apologize! But a lot has happened since then. I graduated from the Flatiron School, moved from New York to San Francisco, and started a new job.

For the past 2 months, I’ve been working at Xamarin as a Mobile Test Automation Intern.

This means I get to author automated UI test scripts for various Android and iOS applications. These scripts then aid in ensuring the highest quality apps by testing them for functional bugs and UI mishaps across various devices in a burgeoning product called the Xamarin Test Cloud.

In a previous role, I was manually QA testing mobile applications on both platforms, so in a way …things have come full circle. It’s really exciting to apply new skills to a familiar craft.

In the past 8 weeks I have learned so much and I anticipate learning even more. I want to seize the opportunity to write about it. I’m looking forward to covering topics such as testing, QA, BDD, mobile, cucumber, and calabash.

I’m excited to tell you all about it.

Until then!


Hide Your Keys, Hide Your Tokens … Unless Deploying to Heroku

In that case, you have to do a little more than just hide them.

Typically, an API will require a key or authentication token before serving data downstream. It’s logical to avoid committing any of these to a public repo on GitHub, so I often found myself falling into a pattern. I would make hidden files in the assets folder of my project, then .gitignore each one.

It would result in a folder structure that might look like this:

1
2
3
4
5
6
/project
    /lib
      /assets
        .api_key
        .auth_token
        .password

Then in the class that controls all of the API calls, I would do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
Class API

  API_KEY = open('lib/assets/.api_key').read()
  AUTH_TOKEN = open('lib/assets/.auth_token').read
  PASSWORD = open('lib/assets/.password').read

  def some_method
    :user_key => API_KEY
    :user_token => AUTH_TOKEN
    :user_password => PASSWORD
  end

end

I set each relevant piece to a constant to be used in methods throughout the API interactions.

This way feels a little clunky, but it works. As long as you remember to add each hidden file to the .gitignore, it keeps the credentials safe. But as a project grows and it accumulates more authorizations, it becomes a little difficult to manage.

It wasn’t until my group tried to deploy an app to Heroku that we discovered the better way. Heroku makes it simple to deploy a Rails app, but as a result it lacks a lot of the bells and whistles. As a result, it is impossible to log in to the server in a shell to upload each individual hidden file described above.

In order to accomplish the same level of security and function, we can instead use Heroku config variables that will be read at runtime. Heroku has some great documentation on this topic.

It’s very easy to set up from the local shell. Thanks to my teammate David Bella, we were able to figure out what we needed to do immediately.

Just navigate to the root of your project directory and run the heroku config:set command.

For example:

1
2
3
heroku config:set API_KEY=abcefghijklmnopqrstuvwxyz
heroku config:set AUTH_TOKEN=abc123doremi
heroku config:set PASSWORD=p4ssw0rd

That’s all there is to it! If you want to see your setup at any point, just type heroku config to see an output like this:

1
2
3
API_KEY:                     abcefghijklmnopqrstuvwxyz
AUTH_TOKEN:                  abc123doremi
PASSWORD:                    p4ssw0rd

This is great for production, but how can we get the same level of organization and clarity for our development environment? My classmate Scott Luptowski told us about the dotenv gem that assists with that exact problem.

Start by including gem 'dotenv-rails' in your Gemfile in the appropriate groups. We only use it in :test and :development. Then, make a .env file at the root of your project directory. In it, include the assignments for each of the keys, tokens or passwords you want to call.

For example:

1
2
3
API_KEY=abcefghijklmnopqrstuvwxyz
AUTH_TOKEN=abc123doremi
PASSWORD=p4ssw0rd

Rails will be able to call these variables anywhere in the application by using this pattern: ENV['API_KEY'], ENV['AUTH_TOKEN'], ENV['PASSWORD']. The hard coded keys will stay out of your code and you will have one organized place to manage all the necessary information. Just remember to also add the .env file to your .gitignore. The app should now work seamlessly in both local development and production Heroku environments. A simple solution for an important problem!


I Like My Coffee Strong … and My Params Stronger

Before understanding the need for strong params in Rails, let’s take a look at the idea of mass assignment in Ruby.

Mass assignment is a convenient technique rubyists can use to easily assign multiple attributes to an object at instantiation. Yanik Jayaram provides an excellent description of it in his blog post. It uses elements of metaprogramming and the idea of dynamic definition which is artfully described by Emily Xie here.

This pattern becomes extremely useful in Rails when dealing with user input in forms. A sign up form is a great place for this pattern.

Let’s take a look at an example:

Sign Up

And here is the markup used to create that form:

1
2
3
4
5
6
7
<form action="/create"   method="post">
  <input type="text"     name="user[first_name]"            placeholder="First name"      value="">
  <input type="text"     name="user[last_name]"             placeholder="Last name"       value="">
  <input type="email"    name="user[email]"                 placeholder="Email Address"   value="">
  <input type="password" name="user[password]"              placeholder="Password"                >
  <input type="password" name="user[password_confirmation]" placeholder="Confirm Password"        >
</form>

Once the user submits this form, the params hash will inlude all the input values neatly nested as key value pairs within the sub key user hash. Then, it would be appropriate to assume somewhere in the UsersController, there is a method like this:

1
2
3
4
5
6
7
8
9
10
11
UsersController

  def create
    @user = User.new(params[:user])
      if @user.save
        redirect_to @user
      else
        "Error!"
      end
  end
end

Instead of having to individually call the following methods, first_name=, last_name=, email=, and password= to set all of these input values … mass assignment lets us get it done at a higher level of abstraction.

But with this convenience lies a crucial vulnerability. In the form example above, we can assume that this web application is backed by a database with a users table that may have more columns than the form leads us to believe. Perhaps administrators also have user accounts within the application and certain permissions are allocated to them. This could be based on an admin column that takes a boolean value of 0 or 1.

Using this knowledge, we can maliciously change any one of the inputs to alter the admin column instead … even if this wasn’t the original intent of the form. Using Google’s Chrome browser, I can inspect the element of the form and change the email input field to reference user[admin] instead of user[email]

That might look something like this:

Sign Up

1
2
3
4
5
6
7
<form action="/create"   method="post">
  <input type="text"     name="user[first_name]"            placeholder="First name"      value="">
  <input type="text"     name="user[last_name]"             placeholder="Last name"       value="">
  <input type="email"    name="user[admin]"                 placeholder="Email Address"   value="">
  <input type="password" name="user[password]"              placeholder="Password"                >
  <input type="password" name="user[password_confirmation]" placeholder="Confirm Password"        >
</form>

Now when I submit this form, the controller is going to create a record in the users table that is missing my email address. Instead, it will set the admin column to true and give me admin access rights to the application. Depending on the domain, I might be able to see and do a multitude of things I normally couldn’t otherwise. That seems not preferable.

Luckily part of the Rails 4.0 core is a pattern that reinforces the idea of strong params. If we were to generate a scaffold using the user resource detailed above, it would produce 2 methods in the controller that look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Rails 4.0

UsersController

  def create
    @user = User.new(user_params)
      if @user.save
        redirect_to @user
      else
        "Error!"
      end
  end

  private
    def user_params
      params.require(:user).permit(:first_name, :last_name, :email, :password)
    end
  end
end

This pattern illustrates the idea of sanitizing the parameters before letting them get anywhere near our domain model. Instead of directly taking in the params submitted through the internet form in the create method, we will first call the private method user_params (named after the resource). This says it should require a sub key of user (resource name) and then only permit certain keys to make it through to the domain model. In effect, this creates a white list of acceptable inputs or strong parameters.

Now, the worst thing that could happen is a form that is submitted with incomplete user data. I think most would agree that is better than the former scenario.

The Rails scaffold comments on this pattern directly in the controller file:

Never trust parameters from the scary internet, only allow the white list through.

I like to imagine DHH himself saying this to really drive this point home.

So you too should enjoy your parameters and coffee the same way: strong. Your code will be more defensive and the data will be cleaner in the long run.


Additional Resources:

Documentation
DHH’s Blog Post
Pivotal Labs on Testing Strong Params
Strong Params Gem for Earlier Ruby Versions


Yield! In the Name of Blocks

Let’s think it over

In an earlier post, I talked about a few Ruby iterators and how they abstract to become useful tools. As promised, I’m going to further break them down in order to describe the conept of yield in Ruby.

In Ruby, methods are functions that allow code to interact with all different pieces of the program. Compared to spoken languages, you can think of methods as the verbs which connect to nouns and other words to form sentences. Methods are able to receive a code block which unlocks limitless potential. When defining our own methods, the magic of yield comes into play. If a method expects a block, it can invoke it by using yield.

For example:

1
2
3
4
5
6
7
8
9
10
11
class Weather
    def initialize(type)
         @type = type
    end

    def forecast
        yield(@type)
    end
end

today = Weather.new("hot")

Here I am defining a weather class that takes an argument at instantiation. I’ve also defined a method forecast that will take any block given and pass it the argument.

1
2
3
4
5
today.forecast do |type|
  puts "It's going to be #{type}!"
end

# => It's going to be hot!

As you can see, I’ve interpolated the variable with a friendly little forecast sentence.

But I could just as easily use a different block to perform a different function.

1
2
3
4
5
today.forecast do |type|
  puts "It's going to be #{type.upcase}, #{type.upcase}, #{type.upcase}!"
end

# => It's going to be HOT, HOT, HOT!

In this case… I am loudly saying it’s going to be fairly warm.

Building on this idea, you can see that it essentially allows any method to easily become an iterator. Here is another look at the iterators described in my previous post: each, collect, select.

each dissected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def my_each(array)
  i = 0
  while i < array.length
    yield(array[i])
    i += 1
  end
  array
end

my_each([1,2,3,4,5]) { |x| puts x * x }

# OUTPUT:
# 1
# 4
# 9
# 16
# 25

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

collect dissected:

1
2
3
4
5
6
7
8
9
10
11
12
13
def my_collect(array)
  i = 0
  collect = []
  while i < array.length
    collect << (yield(array[i]))
    i += 1
  end
  collect
end

collect_results = my_collect([1,2,3,4,5]) { |x| x * x }

=> [1, 4, 9, 16, 25]

select dissected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def my_select(array)
  i = 0
  select = []
  while i < array.length
    if (yield(array[i]))
      select << array[i]
    end
    i+=1
  end
  select
end

select_results = my_select([1,2,3,4,5]) { |x| x == 3 }

=> [3]

BONUS none? dissected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def my_none?(array)
  i = 0
  while i < array.length
    if (yield(array[i]))
      return false
    end
    i += 1
  end
  true
end

my_none?([1,2,3]) { |x| x == 3 }

=> false

my_none?([1,2,3]) { |x| x == 4 }

=> true

BONUS include? dissected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def my_include?(array)
  i = 0
  while i < array.length
    if (yield(array[i]))
      return true
    end
    i += 1
  end
  false
end

my_include?([1,2,3]) { |x| x == 3 }
=> true
my_include?([1,2,3]) { |x| x == 4 }
=> false

These examples are simple and isolated, but yield truly provides myriad possibilities when building sophisticated programs. To prove it, check out this blog post by Michael Bleigh where he described constructing eloquent looking code to design a DSL (Domain Specific Language) with the help of yield.

Have you ever used yield to do something clever or noteworthy? Sound off in the comments!


Abstraction and 3 Helpful Ruby Iterators

I’ve never been a big fan of modern art. Some pieces are so abstract that I don’t really get the point – and I know I’m not the only one.

But in programming, abstraction is different. It makes for more eloquent and productive code by concealing complexity. Let’s witness abstraction by stepping through 3 related methods: each, collect & select.

The each method:

1
2
3
4
5
6
7
8
9
numbers_array = [1,2,3,4,5,6,7,8,9,10]

    numbers_array.each do |x|
      print "#{x * 2} "
    end

#output: 2 4 6 8 10 12 14 16 18 20

numbers_array = [1,2,3,4,5,6,7,8,9,10]

The each method iterates through individual elements in the array and returns the original array untouched.

When I first learned the each method, I used it almost exclusively when working with arrays to make the computer do alot of the leg work for me.

Abraham Maslow explains this consequence:

…if all you have is a hammer, everything looks like a nail.

However, since the each method does not change the original array, I started writing alot of code that looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
numbers_array = [1,2,3,4,5,6,7,8,9,10]
odds_and_ends = []

    numbers_array.each do |x|

      if x % 2 != 0
        odds_and_ends << true
      else x % 2 == 0
        odds_and_ends << false
      end

    end

odds_and_ends

=> [true, false, true, false, true, false, true, false, true, false]

Here, I am creating a new empty array, just so I can shovel items into it with the each method. If this feels bulky to you, that’s because it is! Programmers might say this pattern reeks of code smell.

The ruby collect method is a better tool for the job, and it is just an abstraction of the each method.

Here is collect using the example from above:

1
2
3
4
5
6
7
8
9
odds_and_ends = [1,2,3,4,5,6,7,8,9,10].collect do |x|
  if x % 2 != 0
    true
  else x % 2 == 0
    false
  end
end

=> [true, false, true, false, true, false, true, false, true, false]

Note that the collect method returns a new array which I have set equal to “odds_and_ends.”

But what if we only wanted to return a part of the array if it matches certain criteria? In that case, collect no longer the best option.

As you might have guessed, the ruby select method is an abstraction of the collect method. It also returns a new array, with an implicit if clause built in.

Continuing with our example…

If we were to use collect, it would return a messy array including nil values…

1
2
3
4
5
6
7
odds_and_ends = [1,2,3,4,5,6,7,8,9,10].collect do |x|
  if x % 2 != 0
    x
  end
end

=> [1, nil, 3, nil, 5, nil, 7, nil, 9, nil]

…while select gets the job done more cleanly. It uses the implicit if to return only values matching the specified logic:

1
2
3
4
5
odds_and_ends = [1,2,3,4,5,6,7,8,9,10].select do |x|
  x % 2 != 0
end

=> [1, 3, 5, 7, 9]

So remember, abstraction is your friend!

To recap: select is an abstraction of collect which is just an abstraction of each. Use them to freshen up any and all code smell. I’m still working to make sure I choose the right methods.

By the way, if you were wondering where the each method comes from, you would be right to assume it is just another abstraction of simpler ruby properties! In a future blog post, I will go over how all of these iteration methods break down using the yield statement.


TDD

Test-Driven Development: More Than A Buzzword

Before starting programming classes, I had heard of test-driven development (TDD). I was told it was a good practice, similar to the way I was told to eat my green vegetables when I was younger. That’s why up until today, I thought it was just another business buzzword.

Today we began to cover the basic principles of object-oriented programming (OOP). Even in a simple app with 3 related classes, you can begin to see the complexity unfold. With complexity comes fragility … and that’s where TDD comes into play.

Jason Arhart does a good job explaining TDD in his speakerdeck. Essentially, the process entails writing a simple test, letting it fail, and then writing the minimum amount of code to make the spec pass. He deftly sum’s it up in a cyclical diagram describing the “Red”, “Green”, “Refactor” pattern. By following this method, you get a solid baseline of tests coupled with functioning code.

It’s this constant cycle that allows programs and their programmers to evolve. To this end, I think its better to think of it as an upward spiral. With this approach, the process may be a bit slower, but ultimately the sky is the limit.

Jason describes TDD as a process that, “turns the ‘traditional’ on its head.” I consider myself lucky to start learning in an environment where TDD is the convention. It feels great to pass each spec in a test suite and incrementally move from red to green. I liken it to the feeling you get when gambling and winning, only here you get to bet with the house.

If you want to learn more about TDD, Jason has another speakerdeck that describes the Ruby specific testing framework: RSpec. We will be using more of RSpec as the semester continues at the Flatiron school.


Just Keep Climbing…

It’s been one week since the semester began. In that short time span there have been highs, lows, and countless lines of code mistakes in between. Each night I leave feeling drained. At times, I have been concerned that I might not be keeping pace with my classmates. Still, each morning I wake up energized looking forward to get to school.

In a class-wide retrospective dubbed “Feeling Friday”, I learned that my peers have the same worries. Avi wisely mitigated our concerns by offering some perspective. He assured us that as long as we are constantly exploring, practicing and trying… we would be just fine. He went on to explain that the high and lows are just factors of learning in general. Each peak represents the gratification that comes directly after learning something new. Each low is just a representation trying to learn something new.

Suddenly, pace is irrelevant. We’re all on this journey with and not against each other. The peaks and valleys may come at different points for different people but they will come. The ascent can sometimes be arduous but it is often mostly just fun. The view from the top is extremely enticing.

That elusive feeling of elation is what keeps me coming back. I can’t wait to hit that next peak.


Hello World

Hello World – I’ve written that simple phrase out so many times during the exercises in the Flatiron School prework. However, this time it’s different. It certainly feels good to finally say that to something other than the terminal or console.

Over the course of this semester, I’ll be blogging about my learning experience at the Flatiron School. I’ll do my best to explain some of the topics we cover in order to help and inspire other hopeful developers. Thank you in advance for reading!

And just so we’re acquainted, you should know I’ve decided to become a web developer because …

I’ve been an Internet consumer since before AOL discs ever came in metallic cases. The dial-up connection crescendo still echoes in my mind. Throughout my life web technology has always made things better and easier. Dropbox helped me collaborate on group projects in school. YouTube taught me how to use Excel for my career in finance. I worked for an online dating startup that simply could not exist without it. Now I’m motivated to do more than consume by learning how to code. I hope to pay my love for the web forward with the things that I make in the future.

So again, hello world and hello readers!