Lukas Z's Blog

Ember.js Code-Walkthrough (Video)

Because I was working a lot in the (Rails-) backend lately, I decided to find myself a small frontend-centered side-project that I could work on in my spare time. Because I think that Yehuda, Tom and the others are clever people, I chose Ember.js.

The idea was a small application for salespeople. And now, after a week, I am actually pleasantly surprised how little code I had to write to make it work.

However, I did have to really do a lot of digging through their docs, the ember-sources and ask silly questions on StackOverflow and in the emberjs irc-channel, in order to figure out how to make my app work. There isn’t too much good documentation available now, it seems. Even the Peepcode-tutorial (naturally) didn’t answer all my questions.

So I thought it would be good idea to make a little code-walkthrough video myself. To, hopefully, help the next guy or girl who wants to learn Ember.js.

So yes, here it is:

UPDATE: Contact me if you want a high resolution version of that video. I’ll send you a link.

Ha. I seem to sound a little Russian when I speak English!

And here’s the source-code if you want to download it.

I am obviously a total Ember.js-noob, so don’t take my word for it that I am doing things properly. (I am probably not.) Consider this a little snapshot of one man’s learning progress.

Perhaps I will write an update or make an updated video to show you new things I have learned.

I also have some links with regards to ember.js here.

EDIT: (March 26th , 2013)

I have reverted a merged pull request, because it introduced a bug. Example-App should work fine now.

Multi-Clipboard in OSX

The registers in Vim were always one of my favourite features. It’s like having multiple clipboards. You can copy a string into a register and then copy another. Then both strings are available for pasting. (Not just the last one.)

Today I was going back and forth between applications and decided to find something similar for OSX. It turns out there are quite a few apps one can use.

I have decided to try Clip-Menu, because it’s free, because it handles more than just text and because has a built-in snippet manager.

A screenshot of ClipMenu

Snippets are great. You define keywords for text that you use often.

For example I could define a snippet with the key “hello” and a text “Hello, how are you?”. Then, in the case of Clip-Menu, I just open the Snippet-Manager with ⌘⇧B and select the snippet “hello”, which in turn pastes the “Hello, how are you?” into whatever input field is active at the moment. Useful.

But back to multiple cliboards..

It’s simple. You just copy things like you would normally do using ⌘C and ClipMenu remembers all of them. Then when you want to paste the last thing you copied, you can still use ⌘V, but you can also press the ClipMenu-Hotkey ⌘⇧V (easy to remember, I think) and a popup appears that lets you select one of the things you copied before.

I recommend you give it a try.

As always, there are alternatives for Linux and Windows, which you’ll have to google yourself.

Custom Wrapper-DIV in Octopress

After writing the last post I wanted to add a div that would wrap the email I pasted so I can add some custom style to it. But if I just surrounded the markdown that made up the email with div-tags, then markdown would no longer render the contents and everything inside the div would be displayed as plaintext.

So enter Liquid::Block. The plan was to wrap the source that I wanted wrapped in a div using a liquid-tag.

I dug trough the source of Tobias Lütke’s Liquid to understand how to do it, but I obviously have some more digging to do. However, it’s probably quite clever. Basically, liquid allows to write secure markup that doesn’t eval anything. Everything that inherits from Liquid classes seem to have all methods unset which allows only calls to specifically defined methods.

Well, anyway. I’m sure there’s much more to it, but here’s my tiny little Octopress-plugin that just wraps the contents in a div. Since I’m using markdown, it will only work with markdown.

module Jekyll
        class CustomDivBlock < Liquid::Block
                def initialize(name, params, tokens)
                        @klass = params.strip
                        super
                end

                def render(context)
                        output = RDiscount.new( super ).to_html
                        "<div class='#{@klass}'>#{output}</div><div class='after_#{@klass}'></div>"
                end
        end
end

Liquid::Template.register_tag('customdiv', Jekyll::CustomDivBlock)

It can be now used like this is an Octopress source-file (the quote is from William Gibsons “Neuromancer”, btw.):

{% customdiv paper %}
“All the speed he took, all the turns he'd taken and the corners he'd cut in Night City, and still he'd see the matrix in his sleep, bright lattices of logic unfolding across that colorless void...” 
{% endcustomdiv %}

Here’s the result of the above:

“All the speed he took, all the turns he’d taken and the corners he’d cut in Night City, and still he’d see the matrix in his sleep, bright lattices of logic unfolding across that colorless void…”

It’s probably the “Hello World” of Octopress-plugins, but hey. Next time I have some time off, I’ll just read some more and revise / awesomify this plugin.

Encrypt Your Email With GPG

It’s 2013 and the way we use technology is moving in the wrong direction when it comes to privacy.

We should not accept that in the era of Facebook and Google Search privacy is a thing of the past. Because we cannot blindly trust corporations to handle our private data. Because we cannot assume the government does what is best for us, either. On the contrary. My understanding of democracy is that the public keeps an eye on what the government and public authorities do.

The fact that we live in a mostly peaceful world with a high living standard and low corruption (I am talking of western European countries here) is a huge achievement and a consequence of horrible wars (which had a huge impact on mentalities) and positive economic development afterwards. But looking at history it is an exception. An unlikely thing that happened. Meaning: Because things went well for my generation there is no guarantee that it will continue to be so.

I am an optimist and I do not expect a big catastrophy or another Adolf Hitler in Europe any time soon. But that does not mean that we can be lazy, put our fates (and our data!) in the government’s (or some corporation’s) hands and hope for the best. That would be a stupid thing to do. Our private information should remain private.

Some people still say things like: “I don’t have anything to hide anyway, so I don’t care.” This infuriates me. Especially when it is coming from educated people that should know better.

It is hard to maintain privacy nowadays. For example, last week Facebook suggested in an E-Mail that I “friend” some people that are only in my GMail contacts. - Wait. How did Facebook access my contacts? I haven’t given them the permission. But, and that’s the thing, my contacts gave theirs. In the end it seems that one cannot escape the data collection.

But we should do what we can, without missing out on all the benefits the Internet gives us.

So let me talk about email-encryption.

Why should you encrypt your email?

The Internet works, because many computers form a network of connections. Data is passed from point A to point B by sending it from one intermediary computer to the next. An email will pass through 10 to 20 computers before it reaches its destination.

Those computers include the switch of your DSL provider, their backbone routers, border gateway routers that connect larger regions (countries), the computers of the recipient’s email provider and so forth. Not to mention the guy that sits next table from you in the cafe, using the same unencrypted wireless network.

As a methaphor you can imagine this: You want to send the tax office your income statement. But the mail system doesn’t exist. So you write it with a black marker in big letters on a sheet of paper. For example: “I earned 1000 Euros last month.” Then you give that letter to your neighbor and ask him to give it to the lady next door, so she can then take it to her friend, who works at a store where an accountant from the tax office comes to do his shopping. Of course everyone in that chain can read your income statement. And this is basically how email works.

Your email is sent in plaintext.

Theoretically it can be read, copied and archived forever at any computer it passes through. It’s like sending a postcard. You would put a letter in an envelope, but the postcard can be read by anyone that takes a look. There’s basically no protection against eavesdropping. And no, the fact that you have to use your password to login to your webmail means nothing. The message still travels in plaintext through wires that you have no control over until it reaches your webmail provider’s servers.

(Technically email providers can secure the communication between each other, but this would only work if both sides support that functionality. I assume that is not a widespread practice yet. And besides, even then you would still have to trust the email provider..)

Think about what is being sent in emails. Invoices, contracts, company secrets, passwords and so forth. We rely heavily on email being secure, yet it is, by design, absolutely not. There’s no protection against eavesdropping at the transport layer.

Thus it’s prudent to put in some protection at the application layer. Enter email encryption.

It’s not complicated. Read on.

How can you encrypt your email?

Sadly, encryption was not built in as a default when email was invented. But that was in the 1960s and I guess they did not anticipate that something like the World Wide Web with billions of users would exist in the future. Therefore users have to take extra steps to encrypt their emails. But luckily there are good tools for that.

Using GPG, which is a standard open source encryption software, we can encrpyt every email using public key encryption.

It just means that one key is used to encrypt a message and another is used to decrypt a message. If somebody wants to send you an encrypted message, you just send him your public key first. He can use it to scramble the text. But he cannot use your public key to unscramble it. That can only be accomplished with your private key, which you never send to anyone.

Simple enough.

So basically to have encrypted email you need a key-store on your computer where you store all the keys of your recipients, and your two keys. You can upload your public key to a keyserver, where other people can just look it up if they want to send you something. For example, here’s the new one I just created if you want to email me.

And you also need the encryption software.

I am using OSX, so these instructions are for that OS. You can find the same information for Linux and Windows, it’s equally simple to do.

Here we go.

  1. Download and install GPGTools
  2. Follow their tutorial

That’s it.

Now, they will install an addon to the Mac’s Mail application that allows easy encryption and decryption. But it seems like it’s not done yet for Mountain Lion.

And besides, perhaps, like me, you prefer your email in the browser. In that case you will have to copy the email text out of the message and decrypt it manually. And the same vice versa when you want to encrypt a message. Write, encrypt, copy and paste into the browser.

I wrote these two short bash functions to help with that. They are aliases for gpg commands combined with using the clipboard. It saves me some typing. You can just put those in a file called “cryptobash.sh” or something similar, and then add “source ~/.cryptobash.sh” to your .bash_profile so they are available each time you open a terminal.

function decryptc(){
  pbpaste > /tmp/encrypted_message.txt; gpg -d /tmp/encrypted_message.txt | pbcopy; rm /tmp/encrypted_message; pbpaste
}

function encryptc(){
  pbpaste | gpg -e -a -r $1 | pbcopy
}

Now all I have to do is copy the encrypted email into the clipbard, and run decryptc (c stands for clipboard) in the terminal to see the plaintext. (If you are in on Linux, then you can use xclip instead of pbcopy and pbpaste.)

And voila, encryption isn’t such a big chore any more.

Key Storage

Keeping your keys safe and moving them between computers can be annoying. You have to protect your private key by all means, but you might want to have it available on another computer, for example in the office of your employer.

The way I do this is simply by storing it in KeePass. The KeePass-database file itself is encrypted, so I just put it into my Dropbox and have everything handy wherever I am.

Finally

There’s some downsides to all this of course. If you are using GMail, you cannot search the contents of your encrypted messages anymore. (Unless you specifically save the plaintext in GMail.) You can’t read your encrypted email on your phone as easily either.

But it’s probably not neccesary to encrypt everything. I won’t try to convince my parents to use GPG for example. And I don’t need to encrypt a link to a funny picture that I send to friends either.

However, I wish that people will start encrypt important things. Bank statements. Insurance documents. Spicy love letters. :) And so forth.

To be honest, I do not have much hope for that to happen soon. But who knows, a few privacy scandals, governments messing up (the Internet IS a threat to governments) and the general public might start to ask for secure email. Then perhaps companies will make a greater effort to make it easy (and fun?) to use.

Until that happens we can still send encrypted email already.

So we don’t have to send important things using the equivalent of postcards.

Does Email still matter?

Teenagers probably hardly use email at all. They have things like Skype, Whatsapp, Snapchat etc. But I think email will stay as the main communication tool in business and as a fallback and authentication method for all the other services. So when these teenagers grow up and get jobs they will use email. So yes, it still matters and will continue to do so.

Use Media Queries in Your CSS Now

So far CSS3 has given web developers some great new features. One of the newest W3C standards are Media Queries. And they should be used right now.

The idea is that you can specify style rules in your stylesheets that only apply to devices with certain characteristics. Thus, for example, you can make the same HTML-element render one way in the desktop browser, and another way on the smartphone.

This is fantastic. Some time ago the webserver would parse the HTTP-request to figure out what device the request comes from and serve a different stylesheet. Now we can let the user’s browser worry about that.

How it works

There’s several ways to define device-specific CSS:

  • In the link (or ?xml-stylesheet)-element, by adding a media-attribute to the tag.
  • In the @import-statement, by attaching a media type.
  • As a selector in the CSS-file.

The first two look like this:

<link rel="stylesheet" type="text/css" href="/stylesheet.css" media="print">

or

<?xml-stylesheet media="print" rel="stylesheet" href="stylesheet.css" ?>

And they instruct the browser to use a certain stylesheet under certain conditions. But let’s focus on the third way.

Basically, you just wrap certain elements in @media selectors. For example, let’s say you have a rule like this in your stylesheet:

#somediv {
  width: 900px;
  font-size: 16px;
}

This would probably look crappy on a handheld, because it would require horizontal scrolling. But now you can simply add another rule that makes the div render differently on a device with a smaller screen. So for example we now have this:

#somediv {
  width: 900px;
  font-size: 16px;
}

@media screen and (max-device-width: 800px) { // or something like this
  #somediv {
    width: 90%;
    font-size: 13px;
  }
}

Voilà, this will render a div with 90% parent div-width (let’s say screen width) on an iPhone, but exactly 900px on a desktop. Fantastic. And you can use these queries to change your whole layout, too. Just access this blog with a handheld, and you will see a different layout, without the sidebar etc. Or just make the browser window smaller. You should see the layout change at some point.

I’ve been writing HTML since the 90s, but lately it’s really getting good. Media Queries are definitely one of the reasons.

Media Features

There’s more than just “max-device-with”. The list includes:

  • color (interesting when considering that your page might be displayed on something like a Kindle.)
  • device-aspect-ratio
  • orientation (landscape or portrait)

..and so forth. Check out this list. Scroll a little bit up on this page to see a list of media types.

Read more

For more information do visit the official W3C recommendation page for media queries.

Twitter Cards and Open Graph Metatags in Octopress

To continue on the topic from the last post, here is how I added Twitter-cards and open graph metadata to this blog.

It runs on Octopress so to add the new html-tags I edited source/_includes/head.html like this:


<!-- ... omitted beginning of head.html -->

<head>
  <meta charset="utf-8">
  <title>{% if page.title %}{{ page.title }} - {% endif %}{{ site.title }}</title>
  <meta name="author" content="{{ site.author }}">

  {% capture description %}{% if page.description %}{{ page.description }}{% else %}{{ content | raw_content }}{% endif %}{% endcapture %}
  <meta name="description" content="{{ description | strip_html | condense_spaces | truncate:150 }}">
  {% if page.keywords %}<meta name="keywords" content="{{ page.keywords }}">{% endif %}

  {% capture canonical %}{{ site.url }}{% if site.permalink contains '.html' %}{{ page.url }}{% else %}{{ page.url | remove:'index.html' }}{% endif %}{% endcapture %}
  {% capture ogtype %}{% if page.title %}article{% else %}blog{% endif %}{% endcapture %}

  <!-- twitter card -->
  <meta name="twitter:card" content="summary">
  <meta name="twitter:site" content="@lukaszielinski">
  <meta name="twitter:creator" content="@lukaszielinski">
  <meta name="twitter:title" content="{% if page.title %}{{ page.title }} - {% endif %}{{ site.title }}">
  <meta name="twitter:url" content="{{ canonical }}">
  <meta name="twitter:description" content="{{ description | strip_html | condense_spaces | truncate:150 }}">

  <!-- open graph -->
  <meta property="og:title" content="{% if page.title %}{{ page.title }} - {% endif %}{{ site.title }}"/>
  <meta property="og:type" content="{{ ogtype }}"/>
  <meta property="og:url" content="{{ canonical }}"/>
  <meta property="og:site_name" content="Blog of Lukas Zielinski"/>
  <meta property="og:description" content="{{ description | strip_html | condense_spaces | truncate:150 }}"/>

  <!-- ... omitted rest of head.html -->
</head>

If you are using a theme you will probably have to edit the file .themes/theme_name/_includes/head.html.

Reminder: Put Semantic Data on All Your Pages

Just a quick reminder for all you web-devs out there: Put semantic metadata on all your pages.

Here’s the three usual suspects that I consider most important:

  1. Rich Snippets, there is a handy testing tool from Google
  2. Twitter Cards, there is a Twitter preview tool
  3. OpenGraph

In case you don’t know why you should care: If someone posts a link to your page or if it shows up in search results, it will look better and give the user more information on what to expect when they click it.

Just for fun, you can create a helper to do that. Here’s my crappy version (which doesn’t support Rich Snippets, because they have a different purpose and usage):

require 'rubygems'
require 'action_view'
require 'erb'

class MetadataHelper

  include ActionView::Helpers::TagHelper

  def initialize( opts = {} )
    @title        = opts[:title]
    @url          = opts[:url]
    @description  = opts[:description]
    @image_url    = opts[:image]
    @author       = opts[:author]
    @name         = opts[:name]
    @type         = opts[:type]
  end

  def old_school
    Array.new.tap do |arr| 
      arr << ttag( @title )
      arr << mtag( 'description', @description )
      arr << mtag( 'author', @name )
    end.compact
  end
  
  def twitter_card
    Array.new.tap do |arr| 
      arr << mtag( 'twitter:card', 'summary' )
      arr << mtag( 'twitter:url',  @url )
      arr << mtag( 'twitter:title', @title )
      arr << mtag( 'twitter:description', @description )
      arr << mtag( 'twitter:image', @image_url )
      arr << mtag( 'twitter:author', @author )
    end.compact
  end

  def open_graph
    Array.new.tap do |arr| 
      arr << mtag( 'og:type', @type )
      arr << mtag( 'og:url',  @url )
      arr << mtag( 'og:title', @title )
      arr << mtag( 'og:description', @description )
      arr << mtag( 'og:image', @image_url )
    end.compact
  end

  def all
    [ old_school, twitter_card, open_graph ].flatten.join( "\n" )
  end

  private

  def mtag( name, content )
    tag( :meta, { name: name, content: content }, false, false ) if name && content
  end
  
  def ttag( content )
    content_tag( :title, content ) if content
  end

end

template = ERB.new <<EOS
<!DOCTYPE HTML>
<html>
  <head>
    <%= helper.all %>
  </head>
  <body>
    <p>Hello people!</p>
  </body>
</html>
EOS

helper = MetadataHelper.new( { 
  title:        'Test', 
  url:          'http://www.lukaszielinski.de', 
  description:  'Just testing',
  type:         'article',
  author:       '@lukaszielinski',
  name:         'Lukas Zielinski',
  image:        'http://mugs.mugbug.co.uk/500/mb.i_love_html_red_love_heart.coaster.jpg'
} )

puts template.result( binding )

And yes, I know, I have to put it on all my pages, too. But the day only has so many hours..

Attach a vCard to Your Emails

I received an email with an attachment the other day. It was a .vcf file and I tapped it. Immediately the dialog for adding new contacts popped up and I could just add this person to my address book. This is of course very convenient.

This is also not new (It’s probably been around longer than http), but somehow I have completely forgotten about it. Thus this post as a little reminder.

I have started attaching a vCard to my emails. But since GMail doesn’t allow me to add a file to my signature, I simply post a link to my vCard, which the user can click or tap to add me.

It looks like this: http://www.lukaszielinski.de/vCard.vcf

I suggest everyone to add this to their signature. Convenience matters, in business and otherwise.

P.S.: Check out vCard Maker to easily create your vCard without having to type it yourself.

Tagging View for iOS

I’ve been working on my iPhone app for the last few days and it requires the ability for users to tag things. For a moment I thought I can do this with built-in controls, but then I quickly realized I needed a custom control.

So I created a little tagging-class that can be pulled into the storyboard, because it’s just a view. It’s always nice to have something self-contained, so I decided to put it on Github.

Screenshot of LZTagView

You can download it here.

It allows the user to enter a new tag, which will be displayed in a nice bubble. Suggested tags can be supplied, in which case they appear above the keyboard and can be tapped to add.