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:
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:
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:
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_equaltwenty_one?(3,4,5,6,3),true
Since we know how to use the splat operator now, we can solve the problem:
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.
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:
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:
12
:peanut:butter:and:jelly0123
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:
12
:peanut:butter:and:jelly01234
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.
Winter is almost upon us; the perfect time for staying indoors and coding!
Topics covered:
Cloudfront configuration
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:
Safari & Opera browsers = .toff & .otf
IE9+, Firefox, Chrome = .woff
iOS and Android = .svg
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.
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:
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.
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!
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).
gem'sass-rails','>= 3.2'# sass-rails needs to be higher than 3.2gem'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
123
//=requireself//=requirebootstrap//=requiretree
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.
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:
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.
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”.
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:
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.
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!