Yesterday
close or ESC key
Aaron Draplin is a graphic designer and founder of the Draplin Design Company. He’s done work for everyone from his friend’s hot dog company to President Obama himself. He’s also a speaker and co-creator of Field Notes, a popular notebook series among designers. He’s bold, outspoken, and unapologetic about being awesome.
He took a minute to talk with expert teacher, Mat Helme, and threw some knowledge bombs at him. Enjoy!
The full interview will be available tomorrow to all Treehouse Gold Members.
The post Tall Tales From A Large Man – Interview with Aaron Draplin appeared first on Treehouse Blog.
close or ESC key
close or ESC key
close or ESC key
The process to understand API development is generally complicated but should become easier with practice. Social networks like Twitter and YouTube offer XML/RSS/JSON feeds without the requirement of an API key. However, other smaller networking websites like Instagram and Etsy will require developers to sign up for a new API key before allowing them to make requests from the server.
In this tutorial I want to demonstrate a really simple HTML/CSS/JS web application building over the YouTube API. This demo will list a number of YouTube channels which you may click and pull out all the latest videos, plus their related metadata such as views and comments. All of this dynamic page content will be handled via jQuery so you do not need to host anything on a web server. Check out my sample demo to get an idea of what we are building.
Live Demo – Download Source Code
Getting Started
I will skip a lot of the boring HTML so that we can focus more deeply on the YouTube response and how we handle this in JavaScript. The most important HTML section you should recognize is the navigation along with the inner videos content div. I have used specific IDs so that we can target each element and check whenever the user clicks a link, then display that content inside #videos.
<nav id="usersnav">
<ul>
<li><a href="#gotreehouse">gotreehouse</a></li>
<li><a href="#thenextweb">thenextweb</a></li>
<li><a href="#TEDxTalks">TEDxTalks</a></li>
<li><a href="#wearechange">wearechange</a></li>
<li><a href="#RTAmerica">RTAmerica</a></li>
<li><a href="#G4ZDTechTV2">G4ZDTechTV2</a></li>
<li><a href="#NovaCrystallisDotCom">NovaCrystallisDotCom</a></li>
</ul>
</nav>
<div id="videos">
<!-- vids go here -->
</div>
In order for the whole process to work we will need a copy of the latest jQuery library. My demo includes this file from within the ./js/ directory so you won’t need to re-download anything. Also I have kept my custom-written jQuery codes inside the index file instead of moving them to an external JS script. It would obviously be easier to do so when you are running this on a live website, but for my demo it is quicker to study these codes from within the same page.
Pulling Results with jQuery
The first step is to define a set of variables which we need in the script. Then we can handle a click event from the user which is interfacing with any of the navigation links. Each of the anchor elements is using an HREF value containing a hash symbol plus username we need. It is important that we stop this default href from loading by using e.preventDefault() and then pull the value out so we can get the YouTube feed results.
$(function(){
$('#usersnav ul li a').on('click', function(e){
e.preventDefault();
var htmlString = '<ul id="videoslisting">';
var channelname = $(this).attr('href').substring(1);
var ytapiurl = 'http://gdata.youtube.com/feeds/api/users/'+channelname+'/uploads?alt=json&max-results=10';
The handy JavaScript substring() method will create a new string variable starting from the character marker 1(marker 0 is the first character). This removes our hash symbol so that we can now place the username into a generic API call which looks like this: http://gdata.youtube.com/feeds/api/users/CHANNELNAME/uploads?alt=json&max-results=10
The user’s channel name can be accessed to query YouTube and pull out their latest uploads. I am referencing a max results value of 10 and since we are not using pagination. I have not included any other callback methods, either. JSON is the response type we need so that way it’ll be easier parsing all this content inside jQuery.
Building a Loop
PHP and Rails and other programming languages often use logic loops to iterate through data patterns. While loops, for loops, do loops, and other common ideas are not as strict when you would compare them with JavaScript. However the methods for .parseJSON() and jQuery.each() offer the perfect system for looping through all of these results.
$.getJSON(ytapiurl, function(data) {
$.each(data.feed.entry, function(i, item) {
var title = item['title']['$t'];
var videoid = item['id']['$t'];
var pubdate = item['published']['$t'];
var fulldate = new Date(pubdate).toLocaleDateString();
var thumbimg = item['media$group']['media$thumbnail'][0]['url'];
var tinyimg1 = item['media$group']['media$thumbnail'][1]['url'];
var tinyimg2 = item['media$group']['media$thumbnail'][2]['url'];
var tinyimg3 = item['media$group']['media$thumbnail'][3]['url'];
var vlink = item['media$group']['media$content'][0]['url'];
var ytlink = item['media$group']['media$player'][0]['url'];
var numviews = item['yt$statistics']['viewCount'];
var numcomms = item['gd$comments']['gd$feedLink']['countHint'];
htmlString +='<li class="clearfix"><h2>' + title + '</h2>';
htmlString +='<div class="videothumb"><a href="' + ytlink + '" target="_blank"><img src="' + thumbimg + '" width="480" height="360"></a></div>';
htmlString +='<div class="meta"><p>Published on <strong>' + fulldate + '</strong></p><p>Total views: <strong>' + commafy(numviews) + '</strong></p><p>Total comments: <strong>'+ numcomms +'</strong></p><p><a href="'+ ytlink +'" class="external" target="_blank">View on YouTube</a></p><p><a href="'+ vlink +'" class="external" target="_blank">View in Fullscreen</a></p><p><strong>Alternate Thumbnails</strong>:<br><img src="'+ tinyimg1 +'"> <img src="' + tinyimg2 + '"> <img src="'+ tinyimg3 +'"></p></div></li>';
}); // end each loop
$('#videos').html(htmlString + "</ul>");
}); // end json parsing
This code block seems very large but the majority of the content is generating variable names. YouTube will return a lot more information than we need so it would be foolish to create an array containing all the keys. Instead we should make new variables strictly for the content which will be used inside the layout, and then we create a final HTML string to return to the browser.
Each variable block will contain an important section of the final display. We will need the video title, original publishing date, the full-size thumbnail along with each of the 3 mini-thumbs, direct video URL, view count, and also the comments count. The HTML is displayed using an unordered list of items which finishes by applying the HTML content into the #videos container. This is easily accomplished by using the jQuery .html() method.
Parsing & Formatting Numbers
One other final point I’d like to bring up is the ability to parse through each view counter. Return data for videos which have over 1000 views will not include the comma between each set of 3 numbers. I found an excellent solution on Stack Overflow written using pure JavaScript. The function name is commafy() which is wrapped around each of the view count numbers. This will check if the digits are higher than 4 and automatically place a comma where it should be.
These codes are wonderful to use in any number of JavaScript solutions. The questions and solutions on Stack Overflow are always helpful with these kinds of matters. I think it is worth noting that you could write a much simpler function using jQuery or handling this method inside the .each() loop. But if everything is kept inside a separate file then you may not worry as much about the syntax or number of lines.
Live Demo – Download Source Code
Final Thoughts
Many developers who are not familiar with JSON should hit Google and read a few articles on the subject. It is basically JavaScript code which is written in a certain way so that the syntax can be read as data-value pairs. YouTube can present JSON data from their server and using jQuery it is possible to organize this data into the page dynamically. I hope this tutorial may prove useful to anybody who has been interested in developing over YouTube’s API, or any API for that matter. Feel free to download a copy of my demo and see if you can implement a similar method elsewhere in your own projects.
The post Developing over the YouTube API with JSON appeared first on Treehouse Blog.
Day before Yesterday
close or ESC key
Developing mobile apps is not an easy task. It requires professional skills, experience and dedication. Use of mobile phones has increased over the recent years. The number of people owning and using mobile phones all over the world has increased rapidly. People are using mobile phones to access and share information with others in different parts of the world. Many individuals are using mobile phones to browse the internet, access social media, read emails and even order goods and services. As such, mobile phone applications are very important in the development of businesses. For any business to remain competitive, a good mobile app for enhancing communication with the target audience is very important.
Mobile apps development entails coming up with software for low-power devices. This includes devices that are used in mobile phones, enterprise assistants and personal assistants. This software may be pre-installed in the phones during the manufacturing process of downloaded by mobile phone owners. Nevertheless, the best mobile app is the one that meet specific needs of the user. As such, developing mobile apps is a process that entails research to know what the users want. If you are developing apps for use by a business, you have to find out what its needs are and how to meet them.
Basically, many businesses today are looking for applications that will enhance their interactivity with customers and clients. They want applications that will enable them to get feedback from clients with ease. As such, if you intend to venture into the mobile apps development field you must be ready to do some research. Technology is also changing at a very fast rate. The best provider of mobile apps development services should come up with applications that are compatible with latest technology. Generally, developing mobile apps that will be competitive in the market requires expertise, effort and dedication.
close or ESC key
close or ESC key
A vanity URL is a search engine optimized (SEO) URL. Instead of having a meaningless URL like http://storeofthefuture.com/products/2015 wouldn’t http://storeofthefuture.com/products/hoverboard be better and more meaningful?
It’s fairly straightforward to make URLs nicer in Rails. I’ll walk you through the process.
Baby Steps
In Rails the models have a method called to_param. This method gets called when you pass a model into a URL helper like:
<%= link_to product.name, product %>
Or:
<%= link_to product.name, product_path(product) %>
By default the to_param returns the id as a String rather than a Fixnum. Under the hood Rails is calling to_s on the id attribute, which allows us to override this with our own string. To do this we define the to_param method.
class Product < ActiveRecord::Base
attr_accessible :description, :name
def to_param
end
end
Within the to_param method, let’s set a string with the id followed by the name separated with a dash.
class Product < ActiveRecord::Base
attr_accessible :description, :name
def to_param
"#{id}-#{name}"
end
end
This would generate a URL of /products/2015-Hoverboard for a product with the name of “Hoverboard”.
Now what happens in the show action in the ProductsController? The params[:id] is the String of “2015-Hoverboard” and when you do a Product.find(params[:id]) the find method calls to_i. In Ruby when you call to_i on a String it grabs the first part of the String that looks like an integer. So Product.find("2015-Hoverboard") is exactly the same as calling Product.find(2015).
However, there’s an issue with names that contain a space. For example, a product with the name of “Flux Capacitor” would generate /1955-Flux%20Capacitor/, which isn’t very friendly. We should format the names so that we get them all lowercase and replace the spaces with dashes.
We can do that by creating a method called slug. The word slug describes the part of a URL that is made up of human-readable keywords.
class Product < ActiveRecord::Base
attr_accessible :description, :name
def slug
name.downcase.gsub(" ", "-")
end
def to_param
"#{id}-#{slug}"
end
end
So as you can see we just downcase the name and then gsub out the spaces with a dash and then swap the name with slug in the to_param.
So now the URLs are /2015-hoverboard and /1955-flux-capacitor.
Much nicer.
Taking it Further
Now we’ve done only a little bit of work and haven’t altered the database or the controller. Let’s say we wanted to ditch the ids completely from the URLs.
We’ll do this by generating a new attribute called slug, and then manually or programmatically update all the existing products to have a slug.
We’ll first need to create and run the migration.
rails g migration AddSlugToProducts slug:string
rake db:migrate
Then update your model to have :slug as an attr_accessible and validate its presence while ditching the slug method from the previous implementation. We can also just return the slug in the to_param method like this:
class Product < ActiveRecord::Base
attr_accessible :description, :name, :slug
validates_presence_of :slug
def to_param
slug
end
end
Next fire up your rails console and cycle through each product and update the slug in each existing product.
>> Product.all.each do |product|
?> product.slug = product.name.downcase.gsub(" ", "-")
>> product.save
>> end
Now that we’ve done that, we need to modify the controller. The find method looks up products by the id, so for all instances in your controller where you find(params[:id]) on the @product you’d want to find_by_slug(params[:id]). This is because the :id is defined in the routes.rb, not because it is the :id of the object.
$ rake routes
...
product GET /products/:id(.:format) products#show
...
So in the show action in the ProductsController is should look something like this:
def show
@product = Product.find_by_slug(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @product }
end
end
Depending on how you’re using the model in other actions in your controller, you may need update those too.
You’ll also want to update any forms to include a slug field as this is now required to generate a new model. It’s required because without it you won’t be able to generate a URL or find any existing models.
This implementation of creating clear, human-readable and friendly URLs will yield the urls /products/hoverboard and /products/flux-capacitor, which is exactly what we wanted!
A Small Note on Performance
The id column of databases are normally indexed, if not the first things to be checked and indexed when performance issues occur. Finding by id is a fast method for looking them up. However if you have lots of models it may be worth adding an index on the slug to improve performance.
Here’s what you’d add to a migration:
add_index :products, :slug
Conclusion
Depending on how clean you want your URLs, or how much effort you want to go in to cleaning up existing URLs, either one of these strategies will work for you.
The post Creating Vanity URLs in Rails appeared first on Treehouse Blog.
close or ESC key
Making your website ready for Retina display doesn’t have to be a hassle. Whether you are building a new website or upgrading an existing one, this guide is designed to help you get the job done smoothly.
Make it Retina First
The easiest and most time-saving way to add Retina support is to create one image that is optimized for Retina devices, and serve it to non-Retina devices as well.
By now, every modern browser uses bicubic resampling and does a great job with downsampling images. Here’s a comparison of downsampling in Photoshop vs. Google Chrome, using an image from our Growth Engineering 101 website.

There are two ways to let the browser downsample images for you: img tags or CSS background images.
You can have img tags serve the Retina-optimized image, and set the width and height attributes to half of the resolution of the actual image (e.g. 400×300 if the image dimensions are 800×600).
<img src="http://www.example.com/Retina-image-800x600-2x.png" width="400" height="300">
If you use images as CSS backgrounds, you may use the CSS3 background-size property to downsample the image for non-Retina devices.
<div class="photo"></div>
.photo {
background-image: url(Retina-image-800x600-2x.png);
background-size: 400px 300px;
background-repeat: no-repeat;
display: block;
width: 400px;
height: 300px;
}
In both cases, be sure to use even numbers in both dimensions to prevent displacement of pixels when the image is being downsampled by the browser.
When Downsampling is Not Good Enough
Usually, browser downsampling should work quite well. That said, there are some situations where downsampling in the browser might make images blurry.
Here we have a bunch of 32px social icons.

And here is how they will appear, when downsampled to 16px by Photoshop’s as well as Google Chrome’s bicubic filter. It seems that we get better results from Photoshop in this case.


To get the best results for our users, we can create two versions of the same image: one for Retina devices, and another one that has been downsampled by Photoshop for non-Retina devices.
Now, you can use CSS media queries to serve Retina or non-Retina images, dependent upon the pixel density of the device.
/* CSS for devices with normal screens */
.icons {
background-image: url(icon-sprite.png);
background-repeat: no-repeat;
}
/* CSS for high-resolution devices */
@media only screen and (-Webkit-min-device-pixel-ratio: 1.5),
only screen and (-moz-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min-device-pixel-ratio: 1.5) {
.icons {
background-image: url(icon-sprite-2x.png);
background-size: 200px 100px;
background-repeat: no-repeat;
}
}
If you use a background color for small icons, on the other hand, downsampling by the browser works rather well. Here is the same downsampling example with a white background.

Polishing Your Downsampled Images
If you’re still not satisfied with the results from Photoshop’s downsampling, you can go the extra mile and hand-optimize the non-Retina version to get super crisp results.
Below are some examples of images from the Blossom product website that I hand-optimized for those who are still on non-Retina devices.
Borders and Strokes
Here’s an example of downsampling issues with hairlines, where I re-draw the lines of the downsampled image.

View the Retina Version of this Image on Dribbble.


Text
Next, we come to an example of downsampling issues with text. In this case, I manually re-wrote the text “Feature Pipeline” to make the result as crisp as possible.

Retina Version


When details, crisp fonts, and clean hairlines are important, you might want to go the extra mile.
Try to Avoid Images
The main disadvantages of rasterized images are their considerable file size and that they don’t scale well to different sizes without affecting the image quality. Great alternatives to rasterized graphics are CSS, Scalable Vector Graphics (SVG), and Icon Fonts.
If you have any chance to build the graphical elements for your website in CSS, go for it. It can be used to add gradients, borders, rounded corners, shadows, arrows, rotate elements and much more.
Here are a few examples of interaction elements in Blossom that are implemented in CSS. The subtle gradient is powered by CSS gradients, and the custom font in use on this button is Kievit, served via Typekit. No images.

In the following screenshot, the only two images used are the user avatar and the blue stamp. Everything else – the circled question mark, the dark grey arrow next to it, the popover, its shadow and the arrow on top of it – is pure HTML and CSS.

Here, you can see how projects in Blossom appear. It’s a screenshot of a project’s website used as cover on a stack of paper sheets. The paper sheets are implemented with divs that are rotated using CSS.

Also, the circled arrow in the right-hand side of the screenshot below is pure CSS.

Tools
Here are some awesome tools that will help save time when creating effects with CSS.
- CSS Generator: Cross browser CSS3 syntax by @RandyJensen.
- CSS Arrows: CSS for tooltip arrows by @ShojBerg.
- Generating CSS for Sprites: Sprite Cow helps you get the background-position, width and height of sprites within a spritesheet as a nice bit of copyable css. It’s built by TheTeam, and is a real time saver – definitely worth a try.

The primary advantage to SVG is that, unlike rasterized graphics, they scale reasonably well to various sizes. If you’re working with simple shapes, they typically are smaller than PNGs. Often, they are used for things like charts.

Icon Fonts are frequently used as a replacement for image sprites. Similar to SVG, they can be scaled up infinitely without any loss of quality and are usually smaller in size, when compared to image sprites. On top of that, you can use CSS to change their size, color and even add effects, such as shadows.
Both SVG and Icon Fonts are well supported by modern browsers.
Retina-Ready Favicons
Favicons are really important for users who need an easy way to remember which website belongs to which browser tab. A Retina-ready Favicon will not only be easier to identify, but it will also stand out among a crowd of pixelated Favicons that haven’t yet been optimized.
To make your Favicon Retina-ready, I highly recommend X-Icon Editor. You can either upload a single image and let the editor resize it for different dimensions, or you can upload separate images optimized for each size to get the best results.

How to Make Existing Images Retina-Ready
If you want to upgrade a website with existing images, a bit more work is required, as you’ll need to re-create all images to make them Retina-ready, but this doesn’t have to waste too much time.
First, attempt to identify images that you can avoid by using alternatives like CSS, SVG and Image Fonts, as noted previously. Buttons, Icons and other common UI widgets usually can be replaced with modern solutions that don’t require any images.
In case you actually need to re-create rasterized images, you’ll of course want to return to the source files. As you might assume, simply resizing your rasterized bitmap images to be twice as big doesn’t get the job done, because all of the details and borders will become pixelated.
No need to despair – image compositions which mostly contain vectors (i.e. in Adobe Photoshop or Illustrator) are quite easy to scale up. That said, don’t forget to verify if your Photoshop effects in the blending options, such as strokes, shadows and bevels, still appear as you intended.
In general, making Photoshop compositions directly out of vectors (shapes) and Photoshop’s Smart Objects will save you a great deal of time in the future.
How to Optimize the File Size of Images
Last, but not least, optimizing the file size of all images in an application or website could effectively save up to 90% of image loading times. When it comes to Retina images, the file size reduction gets even more important, as they have a higher pixel density that will increase their respective file sizes.
In Photoshop, you can optimize the image file size, via the “Save for Web” feature. On top of that, there is an excellent free tool, called ImageAlpha, which can reduce the size of your images even more with just a minor loss of quality.
Unlike Photoshop, ImageApha can convert 24-bit alpha channel PNGs to 8-bit PNGs with alpha channel support. The icing on the cake is that these optimized images are cross-browser compatible and even work for IE6!
You can play around with different settings in ImageAlpha to get the right trade-off between quality and file size. In the case below, we can reduce the file size by nearly 80%.

When you’re finished setting your desired compression levels, ImageAlpha’s save dialog also offers to “Optimize with ImageOptim” – another great and free tool.
ImageOptim automatically picks the best compression options for your image and removes unnecessary meta information and color profiles. In the case of our stamp file, ImageOptim was able to reduce the file size by another 34%.

After we updated all assets at Blossom.io for high resolution displays and used ImageAlpha and ImageOptim to optimize the file size, we actually ended up saving a few kilobytes in comparison to the assets we had before.
Save Time, Read This Book

If you want to learn more about how to get your apps and websites ready for Retina displays, I highly recommend “Retinafy your web sites & apps”, by Thomas Fuchs. It’s a straight-forward step by step guide that saved me a lot of time and nerves.
Awesome Retina-Ready Sites on the Web

http://kickoffapp.com/

http://www.layervault.com

http://www.apple.com

Thanks for reading! Any questions?
close or ESC key
In this episode of The Treehouse Show, Nick Pettit (@nickrp) and Jason Seifer (@jseifer) talk about iTunes Scrolling and Mobile Shelving.
Here are the links for the week:
Quick ‘n dirty iTunes 11 style scroller – CodePen
http://codepen.io/vaskemaskine/pen/DrdJE
jQuery.Shapeshift
http://mcpants.github.io/jquery.shapeshift/
Packery
http://packery.metafizzy.co/
Pure CSS Peeling Sticky – CodePen
http://codepen.io/patrickkunka/pen/axEgL
Package Managers: An Introductory Guide For The Uninitiated Front-End Developer – Tech.Pro
http://tech.pro/tutorial/1190/package-managers-an-introductory-guide-for-the-uninitiated-front-end-developer
Niice. A search engine with taste.
http://www.niice.co/
jakiestfu/Snap.js · GitHub
http://github.com/jakiestfu/Snap.js/
The post iTunes Scrolling and Mobile Shelving – Treehouse Show Ep 40 appeared first on Treehouse Blog.










