Blackjack? A Rubeque Splat Problem.

"Final Fantasy VII Meteor"

In my previous post, I explained in detail how Ruby handles splicing of an array, specifically index vs. position. I’ve been working through Rubeque problems, and came up against a splat operator problem here. I had seen the splat operator a few times in Rails, but didn’t have a solid grasp on its functionality.

Before exploring the inner workings of the splat operator, and ultimately how to solve the Rubeque problem, let’s review how we can add multiple arguments into a method:

1
2
3
4
5
def sum(num_one, num_two, num_three)
  num_one + num_two + num_three
end

puts sum(1, 2, 5) # => 8

The above example illustrates how to define a set of parameters for one method by separating each parameter with a comma. This code is easy to read, however it isn’t DRY. Think about if you had a class and had to define multiple methods like this, each with multiple parameters. You can see how the above solution would get quickly obfuscated.

So, to DRY up the code, we can use the splat operator. What is a splat operator? This fancy Ruby (also available in Python) operator defines a variable number of arguments (read: an unknown number of argument). It is defined with an asterisk, like so: *args. Using the first example, we could redefine the solution as such:

1
2
3
4
5
def sum *num
  num.inject(0) { |sum, num| sum + num }
end

puts sum(1, 2, 5)

Going through this step by step:
1) Define the sum method def sum.
2) Use the splat operator *num to define an argument num.
3) Whoa, what is inject? Don’t panic… inject simply combines all elements by applying a binary operation, specified by the block ||. .inject can be passed in an initial value, hence the num.inject(0). If we used num.inject(21), then we would begin summing values starting at 21.
4) Define the block. According to the Ruby docs, the block takes in an accumulator value and an element.

What does all of this mean? In plain English, it looks like this:

1
2
3
4
5
6
7
8
9
10
11
sum begins at 0
sum is defined as an array [1, 2, 5]
the first value in the array is passed to num, in this case value equals 1
sum + num => 0 + 1 => 1
sum now equals 1
the second value (2) in the array is passed to num
sum + num => 1 + 2 => 3
sum now equals 3
the last value (5) in the array is passed to num
sum + num => 3 + 5 => 8
sum now equals 8

The Rubeque instructions are as follows: Write a method that takes any number of integers and returns true if they sum to 21, false otherwise. Hint: splat operator.

The final code that we want to match is

1
assert_equal twenty_one?(3, 4, 5, 6, 3), true

Since we know how to use the splat operator now, we can solve the problem:

1
2
3
def twenty_one? *num
  num.inject { |sum, num| sum + num } == 21
end

We did not need to explicitly define the beginning value in this case. Since Ruby 1.9+, the code can be further DRYed:

1
2
3
def twenty_one? *num
  num.inject(:+) == 21
end

I hope you enjoyed reading this post on splat operators. I learned a great deal by writing it!

Splicing Arrays

"Ghost in the Shell"

Merry Christmas and happy holidays. Lately, I have been digging deeper to understand core Ruby principles away from web development. One of the tools that I am using are are the Ruby Koans – a set of fun, challenging problems that build on each other as your progress through levels. As such, solving these problems is a great way to learn about Ruby syntax, and under-the-hood Rubyisms.

I was working through a section in the Koans called “about_arrays”, specifically test_slicing_arays.

For example:

about_arrays.rb
1
2
3
4
5
6
7
8
9
10
11
def test_slicing_arrays
  array = [:peanut, :butter, :and, :jelly]

  assert_equal __, array[0,1]
  assert_equal __, array[0,2]
  assert_equal __, array[2,2]
  assert_equal __, array[2,20]
  assert_equal __, array[4,0]
  assert_equal __, array[4,100]
  assert_equal __, array[5,0]
end

In this example, an array is defined and includes four symbols; peanut, butter, and, jelly. There are a number of assertions to be made. Where the underscore exists, the user submits their answer. For exampl:

about_arrays.rb
1
2
3
4
5
6
7
8
9
10
11
def test_slicing_arrays
  array = [:peanut, :butter, :and, :jelly]

  assert_equal [:peanut], array[0,1]
  assert_equal [:peanut, :butter], array[0,2]
  assert_equal [:and, :jelly], array[2,2]
  assert_equal [:and, :jelly], array[2,20]
  assert_equal [], array[4,0]
  assert_equal [], array[4,100]
  assert_equal nil, array[5,0]
end

The first argument accepts the “lower bound”, while the second argument is the “range of elements” that you want to pull out of the array, beginning with the “lower bound”. So going through the list, I understood up until the last line: ruby assert_equal nil, array[5,0].

So, really, I didn’t understand anything. After a lot of stackoverflow searching, I came across this post.

What is exactly happening here?

In my head, how I thought indices and arrays worked was this:

1
2
  :peanut   :butter   :and   :jelly
     0         1        2       3

Following from this logic, then [], array [4,0] also wouldn’t make sense, yet that is the solution. Swoon

According to the way splicing works, the indices are defined more like the following:

1
2
  :peanut   :butter   :and   :jelly
0         1         2      3        4

It’s now worth noting that finding the range of an array is different than finding index. When an array is spliced, as in array[4,0], the splice does not identify the elements themselves, but places BETWEEN the elements. This is a key distinction from array[4]; here, Ruby is pointing at index 4. This would result in nil. Try it for yourself!

Simply put: slicing and indexing are different operations, and as such, include different operations, and shouldn’t be directly compared.

How to Display FontAwesome in Firefox Using Rails and CloudFront

"5 cm per second"

Winter is almost upon us; the perfect time for staying indoors and coding!

Topics covered:

  1. Cloudfront configuration
  2. Cross-Origin Resource Sharing (CORS) gem

What are we learning?

In my earlier post, I described how to install Twitter Bootstrap in your Rails project. Today, I was updating my portfolio to use CloudFront as a content delivery service. After opening the page in Firefox, I noticed that the FontAwesome icons were missing. This problem did NOT occur when the page was opened with Chrome or Safari. After more than 4 hours of troubleshooting, I had the page loading properly in Firefox. I sincerely hope that this post saves you countless hours and head scratching. Feel free to leave comments or suggestions. ^.^

FontAwesome

When you download FontAwesome, you will notice that there are 4 different files. What are these? FontAwesome comes in multiple formats so the maximum number of users (read: browsers) can see your fonts:

  1. Safari & Opera browsers = .toff & .otf
  2. IE9+, Firefox, Chrome = .woff
  3. iOS and Android = .svg
  4. IE8 and older = .eot

HTTP Caching

Before we dive head-first into setting up CloudFront, it’s worth taking a slight detour to learn about HTTP caching and headers. According to Heroku, “HTTP caching occurs when the browser stores local copies of web resources for faster retrieval the next time the resource is required. As your application serves resources it can attach cache headers to the response specifying the desired cache behavior.” For our purposes, we need to understand cache header.

Firefox and IE9+ reject all cross-site font requests unless some specific headers are set, i.e. “`Access-Control-Allow-Origin“`. In other words, Firefox will not display a font if you use CloudFront to deliver content. For in-depth understanding, read more here and here. We’ll need to figure out a way to allow Firefox access to the fonts.

Configuring CloudFront


Ahhh, we have finally arrived at the meat and ‘taters of this article. Let’s set up CloudFront (if you have questions, refer to this post on Heroku. But first, what IS CloudFront? Many developers use Amazon S3 (simple storage service) to store static assets (e.g. images, javascript, CSS). It is also sometimes used to serve those assets, but this is not recommended because the S3 was not designed to serve files when your website is under heavy traffic. CloudFront is referred to as a Content Delivery Network (CDN), and acts to serve those assets that you stored on S3.

CloudFront setup

  1. Make an AWS account.
  2. Login to your account, and go to CloudFront control panel. Click ‘Create distribution’, and when prompted for the delivery method, select ‘Web’. For now, use defaults. NOTE: If you wish to use CNAME, you must enter your domain under ‘Origin Domain Name’.

Configure CloudFront and Rails

1) In your Rails application, go to config/environments/production.rb.
2) Look for the setting labelled asset_host. This setting is responsible for prepending a domain onto all asset links created via the built in asset helpers.
3) In your CloudFront Management Console, select the distribution that you created. Click the link “Distribution Settings”. Look for the subheader Domain Name, and copy that domain name. In your Rails app, paste in the domain: config.action_controller.asset_host = "< YOUR DISTRIBUTION SUBDOMAIN>.cloudfront.net".

Purge content from CloudFront

We need to create an invalidation in the CloudFront Panel.To read more about why, go here
Let’s find our fontawesome assets. In your terminal, go to: ~/project_name/public/assets and type ls -al fontawesome-webfont-*.*. You should see something like this:

public/assets
1
2
3
4
fontawesomewebfont4d228e1a1ddd570d6380dcd9b1a11d5c.ttf
fontawesomewebfont6cfa562c51325bb1df40b64732dc8699.woff
fontawesomewebfont9169b7b7c593388d41dd3c339df5b86b.svg
fontawesomewebfonte742c0f297e307a74bdf4ca3c19073a2.eot

Back in the CloudFront Panel, choose the tab Invalidations. Click .
"blog.xdite"
Paste in the above assets like this:

1
2
3
4
assets/fontawesomewebfont4d228e1a1ddd570d6380dcd9b1a11d5c.ttf
assets/fontawesomewebfont6cfa562c51325bb1df40b64732dc8699.woff
assets/fontawesomewebfont9169b7b7c593388d41dd3c339df5b86b.svg
assets/fontawesomewebfonte742c0f297e307a74bdf4ca3c19073a2.eot

IMPORTANT Don’t forget to add assets/ in front of the fontawesome.
Click . Now wait for 5-10 minutes CDN cache to become invalidated.

Install the CORS gem

In your Gemfile:

1
gem 'rack-cors', :require => 'rack/cors'
Run bundle.
In your project folder, go to: config/application.rb and add the following:
config/application.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
module Portfolio
  class Application < Rails::Application
  # …
    config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
    allow do
      origins ''
      resource '',
      headers: :any,
      methods: [:get, :options]
    end
  end
  #…
    config.assets.paths << Rails.root.join("app", "assets")
    config.assets.precompile += %w( .svg .eot .woff .ttf )
    config.assets.header_rules = {
      :global => {'Cache-Control' => 'public, max-age=31536000'},
      :fonts  => {'Access-Control-Allow-Origin' => '*'}
    }
  end
end

The first part of this configuration puts the CORS gem at the top of your stack. Confirm this by running rake middleware in your terminal. Any header is now able to be retrieved via the get method. The second part precompiles the FontAwesome assets by specifically looking for their file extension. It also allows font control via the header_rules.

Push to Heroku

You are now ready to push everything up to Heroku. Don’t forget to manually precompile assets, if necessary.

Additional Resources

Rails, S3, and asset sync
HTTP caching with Rails
Rack::Cache

What’s next?

In the next blog, I will explain how I moved this blog over from Heroku to GitHub pages. If this post helped you, feel free to leave a comment. Thanks and good luck coding!

Installing Twitter Bootstrap

Mission: Install and use Twitter Bootstrap with Ruby on Rails

Boss: Twitter Bootstrap

I remember when I first started using Twitter Bootstrap in early Sept 2013. I really had no idea what I was doing, and spent countless hours ineffectively using the CSS files. As a result, I found myself very frustrated and wondering why this plugin was any better than just creating CSS from scratch. While participating in Startup Weekend, a friend showed me what I was doing wrong and my whole approach to using Twitter Bootstrap changed. I dove into the documentation and found a number of inspiring CSS/Javascript effects. In an effort to help others learn from my mistakes, I’ve created the following tutorial to get you started on basic installation and usage in your Ruby on Rails project.

Installation

Installing Twitter Bootstrap in your rails project is mostly as simple as requiring it in your gemfile. However, there are a few flavors that you can install, as well as two versions (2.3.2 or 3.0.1).

Variations include: Twitter Bootstrap Vanilla, Twitter Bootstrap with LESS, or Twitter Boostrap SASS.

For this tutorial, we will install Bootstrap with SASS. In your gemfile, include the following:

GemfileLink
1
2
gem 'sass-rails', '>= 3.2' # sass-rails needs to be higher than 3.2
gem 'bootstrap-sass', github: 'thomas-mcdonald/bootstrap-sass'

Now run bundle install in the command line. This will install version 3.0.1 of Twitter Bootstrap.

Open up your project, and within the folder assets/stylesheets/, rename application.css to application.css.scss. Now add @import "bootstrap"; anywhere in the file.
In assets/javascripts/, make sure the file looks EXACTLY like this:

application.js
1
2
3
//= require self
//= require bootstrap
//= require tree

This will preload all the javascript functionality that is included with Twitter Bootstrap.

Modifying Bootstrap

Now that Twitter Bootstrap has been installed, we can customize the pages by calling in special classes provided by Bootstrap. What do I mean by special classes? This is where the documentation becomes important. Here is where I must stress the importance of following the documentation examples, so that you can easily learn and manifest the Twitter Bootstrap functionality.

Examples

As of this post, I have been using Twitter Bootstrap for two months. In this short time, I have used the following functionality the most:
Jumbotron
Grid System
Buttons

Let’s run through a quick implementation of these key pieces of Twitter Bootstrap.

Jumbotron

This component adds a container component with specific styling to your page, which calls attention to anything written in it. It can be implemented easily by calling a “jumbotron” on a div. It looks like this:

custom.css.scss
1
2
3
4
5
<div class="jumbotron">
  <h1>Hello, world!</h1>
  <p>...</p>
  <p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>

That jumbotron class is all that you need to specify to add this special functionality in your stylesheet! You can also see that there’s another class in this code “btn btn-primary btn-lrg”. I’ll introduce this now.

Buttons

This component, as you have probably guessed, adds great looking buttons into your CSS. Taking the above example, <p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p>, this adds a button by calling “btn”, followed by the color of the button “btn-primary”, and lastly the size is specified with “btn-lg”. There are six button colors: “btn-default”, “btn-primary”, “btn-success”, “btn-info”, “btn-warning”, and “btn-danger”. There are also four sizes: Large:“btn-lg”, Default (doesn’t require any specification), Small: “btn-sm”, and Extra Small: “btn-xs”.

Grid System

This is arguably the most important component of Twitter Bootstrap. This class specification uses a 12 grid system, with responsive scale, to add size and location to DIV classes. I suggest following the link and reading more about this class. The class is called by the following command:

custom.css.scss
1
2
3
<div class="row">
  <div class="col-md-1">This is a medium size, 1 grid column</div>
</div>

The grid system comes in large, medium, small, and extra-small variations.

Templates

Thanks to Twitter Bootstrap’s popularity amongst web developers and designers, a number of free and paid-for templates exist for Twitter Bootstrap v2.3.2 and v3.0. These are a few of my favorite sites:
FREE:
Bootswatch
Bootstrapstyler
PAID:
Wrap Bootstrap
In fact, it’s easy to implement themes from Bootswatch by specifying in your application.css.scss file, @import "bootstrap/Flatly". This will import the Flatly theme from Bootswatch in your project.
I suggest diving deeper into all the benefits that Twitter Bootstrap provides. Try out Font-Awesome and Glyphicons

Links

If you like what you’ve seen so far, try your hand at implementing templates by following this tutorial I created.

Hello, World

Hello, world.

Octopress goodness. In true coding fashion, I had a bit of trouble creating my first post thanks to an error with Rake.

Specifically, when I typed the command $ rake new_post[“Hello world”], I was greeted with the error: You have already activated rake 10.1.0, but your Gemfile requires rake 0.9.2.2. Using bundle exec may solve this.

After a bit of sleuthing around, I tried a few scenarios to fix this error, namely here. However, this work around required that I USE rake. /facepalm
There’s a better fix! In the gemfile, I deleted ‘~> 0.9’ from the Rake gem. Then I went into the gemfile.lock file, searched for Rake, and changed the number 0.9.22 to 10.1.0. Voila, rake now works!