./ codelitt aka Cody Littlewood

Rants, raves, & ramblings about technology innovation, business strategy, & building cool things for the web

Build and Deploy Ruby Microsite With Sinatra on a Linux VPS

This guide should help you build a basic Ruby microsite in Sinatra and then deploy it to a Linux server. At some point in your life developing Ruby you’re going to have to build a microsite, whether static or dynamic. It may be for a client, a campaign, or your own business. Maybe you just want to learn. The point is, you’ll have to do it. Sinatra is the perfect framework for it. I recommend learning Sinatra before Rails anyways because Sinatra forces you to write more Ruby and rely on less magic. Not to mention RoR is overkill for the majority of the sites out there.

We’re going to use the following technologies:

  • Sinatra – Light, lightening fast, and well documented Ruby app framework
  • Sinatra Assetpack – Convenient asset handling with awesome features.
  • Rspec, Capybara – For the test suite this is pretty standard and makes life easy.
  • slim – The most simple and Ruby like HTML markdown language out there. Makes HTML much more readable.
  • Twitter Bootstrap – I can’t recommend this enough. These guys rock and save me so much time finding buttons, writing CSS, and JS.
  • Capistrano – Capistrano is how we deploy at codelitt. You can write the perfect recipe to make every subsequent deployment a breeze, even over multiple servers.
  • Thin in development and Passenger in production Thin is a great and light app server for development and production, but I use Passenger in production. For this type of site, there is nothing to configure and it automatically restarts with Nginx. It’s a no hassle deployment.
  • Nginx – The most amazing piece of Russion engineering. It blows Apache out of the water in handling requests, speed, and static assets.
  • Ubuntu Server 12.04 – All this technology is running on Ubuntu 12.04 Server Edition LTS. I know I’m usually a huge Arch Linux advocate, but frankly Ubuntu what I use on a server because of stability. Currently looking at Debian for my next server though.

Alright so Sinatra has no generators so you’ll need to create the files and directories. You’ll want an app directory for assets, db directory for migrations, and a views directory for the views. I’m calling my app codelitt so before anything get your app directory made and inside of it the other mentioned directories.

mkdir codelitt

cd codelitt

mkdir app db views

You’ll also need your basic files made. Make a file with the same name as your main app directory. This will be the name of your app. The majority of the model and controller logic will go in this file. It’s going to be a large piece of your application.

touch codelitt.rb

We’re using Bundler to handle our gems and dependencies so:

touch Gemfile

Rake file for Rake tasks:

touch Rakefile

In our Gemfile we’re going to put the basic gems which we’ll need to get things fired up.

You may have noticed that this is a bit more built out than a very simple, single-file Sinatra app. You could do the same things in a single file app, but this gets really messy. I prefer to build it in a more modulular approach.

For your environment you’ll want to setup a rvmrc file in the application directory. This ensures that RVM pairs your app with the right versions of your gems and Ruby.

‘touch .rvmrc’

We’re also going to want to create the gemset.

rvm gemset create codelitt

Now edit the .rvmrc file when you cd into your application directory it always uses the same version of gems and Ruby as are installed by bundle in your app.

vim .rvmrc

Inside this file you’re going to enter this with the name of your gemset/ruby version instead of mine:

rvm use 2.0.0-p247@codelitt

Now we’ll initiate a git repo to handle the version control of our development process.

git init

Create a new repo on Github. If you are lost, check out these directions for creating a new repo.

git add --all

`git commit -am “First commit with basic files”

git remote add origin git@github.com:codelitt/codelitt.git

git push origin master

Now we’re going to get our basic gems setup so our app fires up for the first time.

vim Gemfile

Gemfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source 'https://rubygems.org'

gem 'sinatra', '~>1.4.3', :require => 'sinatra/base'
gem 'sinatra-activerecord', '~> 1.2.3'
gem 'sinatra-assetpack', '~> 0.3.1', :require => 'sinatra/assetpack'
gem 'slim', '~> 2.0.1'

group :development do
  gem 'thin', '~> 1.5.1'
end

group :test do
  gem 'rspec', '~> 2.14.1'
  gem 'capybara', '~> 2.1.0'
end

We’ll create and setup a config.ru file to work with bundler so we can install and keep these gems updated easily.

vim config.ru

config.ru
1
2
3
4
5
6
7
8
9
require 'rubygems'
require 'bundler/setup'
Bundler.require

root_dir = File.dirname(__FILE__)
app_file = File.join(root_dir, 'codelitt.rb')
require app_file

run Codelitt

Finally we’ll require the basic files needed and write our first route to our main app file so we can fire it up!

vim codelitt.rb

codelitt.rb
1
2
3
4
5
6
7
8
9
10
11
require 'rubygems'
require 'sinatra/base'

class Codelitt < Sinatra::Base

  get '/' do
    "Hello world!"
  end

run! if app_file == $0
end

Now let’s install all the gems before trying it out locally.

`bundle install’

Start your local server (which in development we have used Thin), by running

ruby codelitt.rb

And then pointing your browser to http://localhost4567

Everytime you change your app file you’ll have to restart your server with ctrl + c and then running that command again, but for css and view file changes you can just reload the page in the browser.

For styling, I really can’t recommend Twitter Bootstrap enough. It makes life much easier, especially for those of us who like to focus on the backend.

Download Twitter Bootstrap here

Now create the css, image, and js directories in your app directory.

mkdir -p app/css

mkdir -p app/js

mkdir -p app/image

Unzip the bootstrap archive you just downloaded and copy the bootstrap files into these directories.

cp ~/bootstrap/css/bootstrap.min.css ~/code/codelitt/app/css/bootstrap.min.css

cp ~/bootstrap/css/bootstrap-theme.min.css ~/code/codelitt/app/css/bootstrap-theme.min.css

cp ~/bootstrap/js/bootstrap.min.js ~/code/codelitt/app/js/bootstrap.min.js

cp ~/bootstrap/fonts/glyphicons-halflings-regular.svg ~/code/codelitt/app/image/glyphicons-halflings-regular.svg

We’ll also create the theme.css file which we can use to edit parts of our site that aren’t taken care of by Bootstrap.

touch app/css/theme.csss

Now we’ll setup sinatra-asset pack to pick these up. You already have it in your Gemfile. You’ll just need to alter a few things in your main app file to make sure it works. You’ll add this to your main app file. Note that we also are now requiring the assetpack and slim gems in our main app file.

codelitt.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

require 'rubygems'
require 'sinatra/base'
require 'sinatra/assetpack'
require 'slim'

class UberUrlShortener < Sinatra::Base
  set :root, File.dirname(__FILE__)

  register Sinatra::AssetPack

  enable :inline_templates

  assets do
    serve '/js',     from: 'app/js'        # Default
    serve '/css',    from: 'app/css'       # Default
    serve '/image', from: 'app/image'    # Default

    css :cssapp, [
      # '/css/bootstrap.css', # bootstrap.less
      '/css/*.css'
    ]

    js :jsapp, [
     '/js/*.js'
    ]

    css_compression :simple
    js_compression :jsmin
  end

........

Now we are going to create our home page. We’re also going to create our basic layout file which will be consistent across the site.

touch views/layout.slim

touch views/index.slim

The slim extension is what you’ll use if you went ahead and added slim to your Gemfile. It’s the templating engine we’ll use in this tutorial.

In the layout.slim we’re going to include all of the basic information of a normal page and then you’ll notice in the main diff that we pull in the specific page with yield.

layout.slim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
doctype html
html
  head
    title codelitt technology innovation
    meta name="keywords" content="codelitt, technology innovation, technology, technologist, consulting, web, mobile, apps, custom operating systems"
    meta name="author" content="Cody Littlewood"
    meta name="description" content="codelitt helps companies innovate like startups and works with them to prototype and build new technology. Our specialty is in emerging technologies and media."
    meta name="viewport" content="width=device-width, initial-scale=1.0"
    link rel="icon" type="image/ico" href="favicon.ico"
    /This next line adds the routes for css from assetpack
    == css :cssapp
  header
    nav class="navbar navbar-default navbar-fixed-top" role="navigation"
      div class="container"
        div class="nav-header"
          div class="navbar-collapse collapse" 
            button type="button" class="navbar-toggle" data-toggle="collapse" data-target="navbar-ex1-collapse"
              span class="sr-only"
              span class="icon-bar"
              span class="icon-bar"
              span class="icon-bar"
            a class="navbar-brand" href="/" codelitt
            ul class="nav navbar-nav navbar-right"
              li
                a href="/" home
              li
                a href="/technologies" technologies
              li
                a href="/contact" contact
  
  body
    div class="main"
      == yield
      ==js :jsapp
  
  footer

Now we’ll add basic content to our index.slim file as a placeholder.

index.slim
1
h1 Hello world!

In your main app file you’re going to change your route to recognise this change. Going forward you’ll use this basic format to add any new pages/routes that you’d like.

codelitt.rb
1
2
3
4
5
6
7
8
9
10
11
.....

class Codelitt < Sinatra::Base

....
# goes at the end of the class before you close it with "end"
  get '/' do
    slim :index
  end
end
......

Now I’m going to assume that you already have Ubuntu, Nginx, and Passenger already set up. If you don’t then follow this guide except don’t worry about installing the rails gem if you don’t want.

We’re going to deploy with Capistrano which is a sweet little diddy that I use for all of my deployments. It automates things. You just need the right recipe. First we’ll add the two gem’s we’ll need to our Gemfile

Gemfile
1
2
gem 'capistrano', '~> 2.15.5'
gem 'rvm-capistrano', '~> 1.3.3'

Run bundle install

And then capify .

This will build the main files you need.

You’ll want to edit your config.ru file so it looks like this for my capistrano recipe.

config.ru
1
2
3
4
5
6
7
8
9
10
11
12
13
14
rure 'rubygems'
require 'bundler/setup'
Bundler.require

root_dir = File.dirname(__FILE__)
app_file = File.join(root_dir, 'codelitt.rb')
require app_file

set :environment, ENV['RACK_ENV'].to_sym
set :root,        root_dir
set :app_file,    app_file
disable :run

run Codelitt

Here is the Capistrano recipe for a near zero downtime deploy. Change the variables for your own app.

config/deploy.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require 'rvm/capistrano'
require 'bundler/capistrano'

#RVM and bundler settings
set :bundle_cmd, "/home/deploy/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle"
set :bundle_dir, "/home/deploy/.rvm/gems/ruby-2.0.0-p247/gems"
set :rvm_ruby_string, :local
set :rack_env, :production

#general info
set :user, 'deploy'
set :domain, 'www.codelitt.com'
set :applicationdir, "/var/www/codelitt"
set :scm, 'git'
set :application, "codelitt"
set :repository,  "git@github.com:codelitt/codelitt.git"
set :branch, 'master'
set :git_shallow_clone, 1
set :scm_verbose, true
set :deploy_via, :remote_cache

role :web, domain                          # Your HTTP server, Apache/etc
role :app, domain                          # This may be the same as your `Web` server
role :db,  domain, :primary => true # This is where Rails migrations will run
#role :db,  "your slave db-server here"
#deploy config
set :deploy_to, applicationdir
set :deploy_via, :export

#addition settings. mostly ssh
ssh_options[:forward_agent] = true
ssh_options[:keys] = [File.join(ENV["HOME"], ".ssh", "id_rsa")]
ssh_options[:paranoid] = false
default_run_options[:pty] = true
# if you want to clean up old releases on each deploy uncomment this:
# after "deploy:restart", "deploy:cleanup"

# if you're still using the script/reaper helper you will need
# these http://github.com/rails/irs_process_scripts

# After an initial (cold) deploy, symlink the app and restart nginx
after "deploy:cold" do
  admin.nginx_restart
end

# As this isn't a rails app, we don't start and stop the app invidually
namespace :deploy do
  desc "Not starting as we're running passenger."
  task :start do
  end

Now ssh into your deploy server and make a directory where you keep your websites called your app name.

mkdir codelitt

Next you’ll need to add the site to your sites-available and then make a symlink to sites-enabled.

touch /etc/nginx/sites-available/codelitt

codelitt
1
2
3
4
5
6
server {
        listen 80;
        server_name codelitt.com www.codelitt.com;
        root /var/www/codelitt/current/public;
        passenger_enabled on;
}

sudo ln -nfs /etc/nginx/sites-available/codelitt /etc/nginx/sites-enabled/codelitt

We’re pulling from the git repository so commit and push your final changes.

git add --all

git commit -am "final changes before deploy"

git push origin master

Now you can deploy your site. The script should automatically restart Nginx for you.

cap deploy

That’s it! You’re all done.

Setting Up an External Monitor on Macbook Pro Running Arch Linux and AwesomeWM

I really don’t need any more power than my Macbook Pro running Arch Linux. The distro is tiny and extremely powerful so with an SSD upgrade, it is more than enough. I do, however, hate spending much time in front of a 13 inch screen. I use my laptop as my work station, but plug in an Apple Cinema Display (already had it, but it is beautiful and huge) and an Apple USB keyboard and mouse. Apple Cinema is a little bit of an overkill really, but I’m a huge fan of their keyboards. They have the perfect amount of give for me.

Here’s the product list:

If you’re wanting the Bluetooth setup, for now you’ll have to check out the wiki.

Dual Monitors

Getting Dual monitors setup with Mini DisplayPort is pretty easy with Arch Linux running AwesomeWM.

AwesomeWM comes with a wicked litle tool called XRandR that handles all of your dual monitor settings. I found it much easier than dealing with Xorg or X11 conf files.

To query your hardware you need to run:

xrandr -q

Your output will list devices availble and what’s connected to what port:

[bash output]
1
2
3
4
5
6
LVDS-0 connected primary 1280x800+0+0 (normal left inverted right x axis y axis) 286mm x 179mm
   1280x800       60.2+
DP-0 disconnected (normal left inverted right x axis y axis)
DP-1 disconnected (normal left inverted right x axis y axis)
   2560x1440      60.0+
   1280x720       59.9

When you check this output, you’ll notice that your LVDS-0 is connected. Your monitor that is plugged in to the DisplayPort is disconnected and lists available display size options. Too connect your monitor, you’ll tell XRandR to output to this screen as well and specify your resolution desired. You can also decide where the monitor will be located in relation to your primary screen. There is more information for alternative settings in the AwesomeWM Wiki.. I ran:

xrandr --output DP-0 --mode 2560x1440 --right-of LVDS-0

You should see your monitor fire up without any issues.

Apple USB Keyboard

A USB keyboard is easy. It should work as soon as you plug it in either to the back of your monitor or directly to the laptop.

Apple USB Mouse

Same thing. Plug and play. I prefer to plug both the keyboard and mouse into the monitor. When I’m arriving or leaving work, I only have to plug/unplug in the power, MiniDisplay and one USB cable to the laptop.

If you run into any problems, head to the comments, the Arch Wiki, or ping me on Twitter @codelitt

Dual Boot Arch Linux on MacBook Pro Installation

The installation process of Arch Linux on a Macbook Pro has quite a few caveats, but it is about the slickest machine I’ve ever run. The only difference in my hardware is the Samsung SSD, but I point out what to leave off if you have an normal HD. The Arch Linux Wiki entry for Macbooks has gotten pretty messy and has a lot of conflicting information. While I’m going to do my best to clean it up and add information that I found helpful, I wanted to document my process as it may be helpful for others as well as provide a personal resource for future reference. I got a lot of good information from other sources so I try to credit them where applicable, but a great resource especially worth mention is this post.

Having an extra computer handy for Google and an ethernet plugged into your Macbook are definitely useful items to have.

Preparing and booting from live USB

The first caveat is with the installation media. It isn’t clear anywhere else, but you do need to do a few specific things to create a live USB which will boot with Apple’s UEFI.

These liveUSB instructions are for Linux. May work in OSx, but might as well just fire up a VM to be safe.

  • First create a partition table with at least one partition on the USB.

  • Mount the Arch Linux ISO image.

mkdir -p /mnt/{usb,iso}

mount -o loop archlinux-2012.05.03-dual.iso /mnt/iso

  • Create a FAT32 filesystem in the partition on the USB. Change LABEL in the code to the one used in the Arch ISO configuration. You’ll find it at:

/mnt/iso/loader/entries/archiso-x86_64.conf

To make the FAT32 filesystem:

mkfs.vfat -F32 /dev/sdXY -n LABEL # e.g. ARCH_201305

  • Mount the newly created FAT32 USB partition and copy the contents of the instalation media to the USB media.

mount /dev/sdXY /mnt/usb

cp -a /mnt/iso/* /mnt/usb

sync

umount /mnt/{usb,iso}

Now you should be able to plug in the USB to your Macbook, hold the option key, and select to boot from the Arch Linux live USB.

Partitioning

People usually get stuck on partitioning as well. There are many options, but the simplest is the best in my opinion. Keep your EFI partition from the Mac (don’t create a separate EFI System partition for your linux drive. They can share the same partition.) Create a small bootloader partition using Apple’s HFS+ filesystem that you will later bless as bootable in your OSx install. You’ll then need a boot partition, root partition, and home partition. A swap partition is optional and I’m not going to go into it.

  • Upon booting from your Arch Linux live USB, run:

cgdisk /dev/sda

  • Then partition your drive according to the table below. Make sure not to touch the first three partions which already exit. You are just creating the new ones:
Part # Size Partition type Partition name
1 200 Mib EFI System EFI system partition
2 93 Gib Apple HFS+ Macintosh HD
3 700 MiB Apple boot Recovery HD
4 128 MiB Apple HFS+ Linux Boot loader from Apple
5 256 MiB Linux filesystem boot
6 100 GiB Linux filesystem root
7 250 GiB Linux filesystem home

Network for installation

Just make sure you’ve had your ethernet plugged in. run ping google.com to make sure it’s up, but you should be good out of the box.

Format partitions and install

mkfs.ext2 /dev/sda5

mkfs.ext4 /dev/sda6

mkfs.ext4 /dev/sda7

mount /dev/sda6 /mnt

mkdir /mnt/boot && mount /dev/sda5 /mnt/boot

mkdir /mnt/home && mount /dev/sda7 /mnt/home

pacstrap /mnt base base-devel

genfstab -p /mnt >> /mnt/etc/fstab

If you storage device is SSD change your fstab file parameters:

[/mnt/etc/fstab]
1
2
3
4
nano /mnt/etc/fstab
/dev/sda5      /boot  ext2  defaults,relatime,stripe=4    0 2
/dev/sda6        /      ext4  defaults,noatime,discard,data=writeback   0 1
/dev/mapper/home /home  ext4  defaults,noatime,discard,data=ordered 0 2

Configure

After everything is installed, set up your hostname, users, and locale.

arch-chroot /mnt /bin/bash echo archer #or whatever you want to call it > /etc/hostname ln -s /usr/share/zoneinfo/America/Buenos_Aires /etc/localtime hwclock --systohc --utc useradd -m -g users -G wheel -s /bin/bash codelitt && passwd codelitt sudo pacman -S sudo

nano /etc/sudoers # uncomment wheel line

To set up your locale, run:

sudo nano /etc/locale.gen

Uncomment the desired locals. For me this was:

en_US.UTF-8 UTF-8

en_CA.UTF-8 UTF-8

Generate these locales by running:

locale-gen

echo LANG=en_US.UTF8 > /etc/locale.conf

export LANG=en_US.UTF-8

You’re going to modify your /etc/mkinitcpio.conf file to insert “keyboard” after “autodetect” in the HOOK section. Then run:

mkinitcpio -p linux

Bootloader

This is probably one of the most confusing sections of the installation process particularly with Macbook’s dual booting. The best way to do this is to boot directly from your Macbook’s EFI boot loader so you’ll need to create a boot.efi.

pacman -S grub-efi-x86_64

  • Alter the /etc/default/grub with:
[/etc/default/grub]
1
GRUB_CMDLINE_LINUX_DEFAULT="quiet rootflags=data=writeback"`
  • Then you can generate the boot.efi with GRUB which you just installed. You’ll want to put this on a USB device because you’re going to be switching into OSx in a minute.

grub-mkconfig -o boot/grub/grub.cfg grub-mkstandalone -o boot.efi -d usr/lib/grub/x86_64-efi -O x86_64-efi -C xz boot/grub/grub.cfg

  • This is going to create a file in which ever directory you are called boot.efi. Place it on a USB device. Check your devices then make a directory to mount your USB. Copy the boot.efi file onto your USB drive.

mkdir /mnt/usbdisk && mount /dev/sdb /mnt/usbdisk cp boot.efi /mnt/usbdisk/

  • Now you can exit chroot with exit and umount all of your filesystems from earlier. Reboot back into OSx.

  • Launch disk utility, select the /dev/sda4. Select erase, select Mac OSx Journaled, and click Erase. This is where your grub2 image will live in.

  • Create directories and files in /dev/sda4.

cd /Volumes/disk0s4

mkdir System mach_kernel

cd System

mkdir Library

cd Library

mkdir CoreServices

cd CoreServices

touch SystemVersion.plist

  • Copy over the boot.efi from the USB stick.

cp /Volumes/usbstick/boot.efi boot.efi

  • Now you need to edit the SystemVersion.plist and add this:
1
2
3
4
5
6
7
8
9
10
11
<xml version="1.0" encoding="utf-8"?>
<plist version="1.0">
<dict>
    <key>ProductBuildVersion</key>
    <string></string>
    <key>ProductName</key>
    <string>Linux</string>
    <key>ProductVersion</key>
    <string>Arch Linux</string>
</dict>
</plist>
  • Now all you need to do is bless this partition to make it a bootable disk.

sudo bless --device /dev/disk0s4 --setBoot

  • Now you can reboot and hold down your Option key. Select the second EFI disk on the list and hit enter to boot into Arch. Do the same but select the first to boot into OSx.

Xorg

The dreaded Xorg server. Luckily it goes pretty smoothly with the right drivers for your video card. You can change settings and play with your touchpad synaptics, backlighting, and everything else later. There is plenty of documentation out there. We’re just going to get it running. Thsetup is for nvidia video card. If you’re running an intel card for video then check the Wiki.

pacman -S xorg-server xorg-xinit xorg-server-utils xf86-input-synaptics nvidia acpid systemctl enable acpid nvidia-xconfig

Sound

ALSA works out of the box with Macbooks. Install alsa-utils:

pacman -S alsa-utils

Then unmute the speakers.

alsamixer

Desktop

Alright. I don’t use a desktop. I just use a WM called awesome. It’s in the official repositories and it is kickass. That’s what I’ll show you how to install.

  • Get some fonts.

pacman -S ttf-dejavu ttf-google-fonts-hg #google fonts recommended but not necessary

  • Install awesome from the official repositories:

pacman -S awesome

  • You’ll want to create a config file because it doesn’t come with one.

mkdir -p ~/.config/awesome/

  • Copy a template file over to the directory you just created.

cp /etc/xdg/awesome/rc.lua ~/.config/awesome

  • There are many different themes available, but for now use the default theme. Change it later if you like. We’ll copy the default theme over and then change the theme_path in the rc.lua config file for awesome.

cp -rf /usr/share/awesome/themes/default ~/.config/awesome/themes/default nano ~/.config/awesome/rc.lua

Change theme_path to:

beautiful.init(awful.util.getdir("config") .. "/themes/default/theme.lua")

  • Before leaving change default terminalline to:

terminal = "xfce4-terminal"

  • Now it makes sense to install this terminal with:

pacman -S xfce4-terminal

  • I don’t use a login manager so add exec awesome to your startup script ~/.xinitrc

  • Now from your tty you can startup your new WM with startx.

WiFi

This part was probably the biggest pain in the ass of my entire install. The drivers don’t load properly at first and everything is just better off when done manually instead of through the package manager.

Thanks to Reddit user jb270 on a thread I found recently and a bit of digging, I found a pretty fool proof way to get things rolling.

  • Download and extract the b43 firmware (https://aur.archlinux.org/packages/b43-firmware/) To extract use tar -zxf b43-firmware.xxx.xx

  • Change into the b43 folder and run this to download dependencies and install the package.

makepkg -si

  • Make sure to unload all known drivers before loading the new one. It can cause headache down the road if you don’t:

modprobe -r b43 bcma brcmsmac wl

  • Now load your new shiny b43 driver.

modprobe b43

  • Run dmesg and grep your wireless card to make sure everything worked fine.

dmesg | grep wlan0

If your interface is not called wlan0 then run ip addr to find your interface name.

  • Now we’re going to disable the normal dhcpcd service and install probably the easiest to use Network Manager.

pacman -S networkmanager network-manager-applet gnome-keyring seahorse

systemctl stop dhcpcd@wlan0

systemctl stop dhcpcd@eth0

systemctl disable dhcpcd@wlan0

systemctl disable dhcpcd@eth0

  • Bring both your ip links down and back up with:

ip link set eth0 down

ip link set wlan0 down

ip link set eth0 up

ip link set wlan0 up

  • You’ll be using the gnome-keyring to save your wifi passwords and since you don’t want the rest of the GNOME desktop, add this to your ~/.xinitrc file:
1
2
3
4
5
6
7
8
9
# Start a D-Bus session
source /etc/X11/xinit/xinitrc.d/30-dbus
# Start GNOME Keyring
eval $(/usr/bin/gnome-keyring-daemon --start --components=gpg,pkcs11,secrets,ssh)
# You probably need to do this too:
export SSH_AUTH_SOCK
export GPG_AGENT_INFO
export GNOME_KEYRING_CONTROL
export GNOME_KEYRING_PID`
  • Now you just need to enable NetworkManager dameons and start the nm-applet

systemctl enable NetworkManager

systemctl start NetworkManager

nm-applet

The applet should appear in the top right hand corner of your awesome windows manager. The rest should be pretty self-explanatory.

The rest you should be able to figure out, but commment here or ping me on Twitter @codelitt

Hey Twitter, Why Are You Spoofing Your Own Users’ Accounts?

Twitter is spoofing users’ accounts in the Discover feed and I’m not sure why. Basically, they are promoting tweets in our Discover feeds by spoofing the reason for the tweet showing up in your personal feed. Twitter looks through your list of whom you are following and then adds “PersonYouAreFollowing follows AccountOfTweet” to the top of the tweet to validate the reason for putting this tweet in your Discover feed. This would be a relatively good thing to do if the tweets in my feed were from accounts that the people I’m following actually follow. The problem is, they aren’t. It’s being spoofed by Twitter themselves. I noticed the spam/spoof when I saw a tweet by a blog on Buenos Aires that supposedly the Pope himself follows in my Discover feed.

Twitter spoofs the Pope

I don’t know much about the papacy, but I kind of doubted that the Pope has a significant amount of time to read up on the tales of the ex-gardener of Nestor Kirchner. Sure enough, if you go look at the Pope’s profile, you’ll see that he only follows his own accounts for the different languages.

I then started looking for other inconsistencies and I found several. For example Louis CK, according to my Discover feed, follows both @huffingtonpost (unlikely, but whatever) and @AVTVClub. Taking a look at who Louis CK follows (1 account), this is obviously not true.

Twitter spoofs Louis CK

Another example of an account being manipulated is one of my personal heroes, Commander Chris Hadfield, a Canadian astronaut and most recent commander of the ISS. You can see from the images below and his following feed that his account is being spoofed as well by Twitter.

Twitter spoofs Chris Hadfield Twitter spoofs Chris Hadfield

Same with The Onion:

Twitter spoofs The Onions

It doesn’t happen with only sponsored accounts as shown here:

Twitter spoofs The Clubhouse

Now maybe none of these people mind, but maybe they do. Perhaps the Pope doesn’t want his followers to wrongly believe that he is following some random blog talking about a former Argentine president’s gardener. I doubt Louis CK wants people to think he is following the Huffington Post and their awesome articles about why Brad and Angelina are on the rocks. Maybe I’m wrong and no one minds, but either way, as a user, I don’t appreciate being lied to or misinformed. It’s seedy at very best.

Twitter has been working pretty consistently on integrating their revenue model of sponsored tweets, sponsored accounts to follow, and sponsored hashtags over the past year. However, these tweets in the Discover feed are not called out as sponsored interactions like the others. They are snuck in amongst everything else and they are inaccurate. At best it’s an engineering mistake. At the worst it’s spam and an inaccurate representation of their users. They also have received criticism for the amount of spam on Twitter. It’s pretty interesting to me that given this criticism they would spam their own system with inaccurate details.

PiFace Digital IO on RaspberryPi With Arch Linux ARM

I’m currently the process of building a RaspberryPi setup to basically control my entire home with a WebUI that I can access from anywhere. I need the capabilities to provide surveillance, control the lights, regulate temperature, and control my media centre/sound system throughout the home. Accessing these controls from any device remotely is a huge appeal; not to mention the convenience and peace of mind.

There are lots of open-source projects for XMBC which will take care of my media centre, a few surveillance projects, and a WebUI project so I figured I’d get started on the lighting and temperature. Luckily there is the PiFace Digital IO which offers a super simple input/output board and plugs directly into your RPi.

If you’re missing either pieces you can pick up the RaspberryPi here and the PiFace Digital IO here.

RaspberryPi with PiFace

There was already a library out there for the board, but I use Arch Linux ARM on my Pi’s. Arch doesn’t come with Python3, make, or gcc preinstalled and the library depends on these. Since I already was going to fork the PiFace library, I decided you add the dependencies into the install script to make it easier for others. It uses pacman to install the dependencies so you shouldn’t have any conflicts or issues.

You can find the PiFace library for Arch Linux ARM here.

Install git with:

pacman -S git

Configure git.

Clone the library:

git clone https://github.com/codelitt/pifacedigitalioArch

Change directories:

cd pifacedigitalioArch

And run the install script:

./install.sh

You may have to sudo if you are not already root. Answer “y” and hit enter when the install script prompts you if the packages are not already installed.

How to Setup Raspberry Pi via SSH With Arch Linux (No Monitor, No Keyboard)

The information provided will help you find your RPi on the network and get you connected and logged in via SSH to your RPi to begin your install and setup. If you don’t already have a Raspberry Pi you can order one here. Once you get to this step, check out the Arch Linux Beginner’s Guide and Arch Linux Installation Wiki for the best information.

Specs:

  • Raspberry Pi board.
  • SSH on your Mac or Linux computer (Macs and most distros come with it preinstalled)
  • SD card loaded with Arch Linux - RPi Easy SD Card Setup (Could be Raspbian distro as well but change SSH login details in steps 8 and 9 to: pi (username) and raspberry (password). I like the Sony Class 10 card, but it’s up to you.
  • Raspberry Pi connected via ethernet to the network.

  • Plug in your RPi and give it about 2 minutes (just to be sure) to get fired up

  • On your Mac or Linux open a terminal. Both come preinstalled. Search “terminal” if you have problems finding it.

  • In the terminal window, search for the broadcast IP on your local network by:

ifconfig | grep broadcast

It should return something like this:

inet 192.168.0.3 netmask 0xffffff00 broadcast 192.168.0.255

  1. Copy the broadcast IP (Mine is 192.168.0.255) and then ping the broadcast IP with this:

Linux:

ping -b 192.168.0.255

Mac:

ping 192.168.0.255

It should begin to return something like this:

64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=46.7 ms 64 bytes from 192.168.0.2: icmp_seq=1 ttl=64 time=74.1 ms (DUP!) 64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=69.8 ms

  1. Use CTRL + c to exit out of the ping

  2. Now to find which other IP’s are connected on your network (one of which is the RPi) run:

arp -a

which should return something like:

? (192.168.0.1) at 21:b3:17:94:f4:71 [ether] on eth0 ? (192.168.0.7) at f3:9e:df:e1:32:34c [ether] on eth0

  1. The first number in each line is an IP of a device connected to the network. Normal routers use what is called DHCP or Dynamic Host Configuration Protocol to “lease” IP’s to devices connecting to the network so they can be identified. If a lease expires or a device removes itself from the network then this frees up the IP to be assigned to a new leasee upon request. In most situations, routers assign IP’s starting from low to high and if your RPi was the last device connected you can make a reasonable guess that it is the highest IP.

Copy this number and use it for the next steps. If these steps do not work then it stands to reason that your RPi is one of the other (hopefully) few IP’s listed. So give those a try before asking a question in the comment section or on Twitter.

  1. In your terminal window run:

ssh root@192.168.0.7 (or whatever IP got from steps 6,7)

  1. It will prompt you for a password, so enter the default Arch password:

root

  1. All done. You are logged in via SSH to your Raspberry Pi and now can continue with installation as normal.

Digital Agencies in NYC - How to Find and Choose the Right Agency for Your Needs

TL;DR- Find the best digital agency by looking for a company with experts, full service (interactive) capabilities, people with strong strategy and business acumen, the right size amount of people, a trustworthy crew, and a passion. I personally recommend Uber Digital.

Everyone wants to find the best digital agency (or agencies) for their business, but once you actually start actively searching weeding out the cruff becomes a much more daunting task…especially since anyone on the internet can really say anything they please. Finding the best digital agency in an over-saturated market like NYC can be an absolute pain in the ass. I’ve worked on both sides of the market. I’ve worked for a large Fortune 500 trying to find a digital agency of record, and I’ve worked for a digital agency. Right now, I sit somewhere in between as a consultant where I’m neither client nor agency, but work closely with both. Here are the things I look for and major watch-outs:

Experts

This seems like such an obvious one, but I can not stress it enough. The agencies I usually steer clear of are the ones who are constantly pitching me something. I’m usually on the bleeding edge, but agencies that can teach me something new, offer new insight, and are able to build connections through networks of ideas are the agencies that will deliver real value in the end. If an agency is annoying you with their pitch, how will their marketing, design, or digital assets be perceived by your customers.

Full service (aka Interactive)

Actually I really hate the descriptor “interactive” to describe an agency or firm that can do everything because it’s really an awful use of the english language and is corporate language that has been diluted into nothing. That being said, you want someone who can deliver on your needs. Whether it’s NDAs, RFPs, on-boarding education, or countless other items every agency that you have to bring on inherently adds another layer of complexity and time. You want a shop who just can get things done and done well. A shop who envelopes strategy into a fully integrated execution is going to be far more valuable than a shop who just builds your specs. A shop that can look at all aspects of your business, help you identify opportunity, develop a strategy, develop wireframes for a website and storyboards for a video, then execute and provide you with these beautiful assets in a neat package is a shop I will hire every single time.

Strategy and business acumen

I could possibly put this into the section above, but it’s honestly so important that I decided to keep it on its own. There are hundreds of agencies in NYC that can execute (how well they execute is a different matter). The problem with digital agencies is that it’s honestly such a new game that they get too wrapped up in what is going on in their world that they forget that there is still a business to run. Usually this means they want to build something shiny, but not for the right reasons. Chasing shiny is great for brainstorming, but unless you can tie it to actual business value, then it’s a just an exercise and wasted money.

Size matters (but not the way you think)

There are many big names in digital agencies (particularly in NYC), but unless you are spending $1 million on a project with them, chances are that you’re going to be getting a B team with a large agency. Even if you are spending $1 million+, you are a new client. Agencies tend to take care of the clients that are directly tied to steady cash flow. Over time you may transition into an A team, but you certainly won’t be getting it at first. With a small (but ample) agency, they don’t have room for B teams. B players are quickly weeded out and let go. Junior members of the team may grind their teeth on a smaller project, but everything is ran through a Senior employee with years of experience who guarantees that the quality of work meets their standards. Now small doesn’t mean stretched. You want to be careful and make sure that the team can handle the workload (or hire to accommodate for it). Steer clear of agencies who are one or two man shops if they have other clients. This can be dangerous. If you have a massive project, make sure there is at least one Senior person for every area of expertise (design, strategy, technology) and the employees to handle the workload. Many medium sized firms have small branches in different locations, but as a whole they have the team to support your needs.

Trustworthiness and personality

These almost go without saying, but quite frankly there are a lot of slimey players since this is a relatively new industry. You’ll get the “social media marketing experts” and the spammy snake oil salesman on far too often of an occasion. Look for people who you would like to go out with for drinks. You will be spending a lot of time with these people. You want someone who you can trust, both to get the job done and to be looking out for your best interest. Finding a digital agency who is genuinely concerned with the best interests of your business is going to pay off in dividends later on. Ask for references and press the references, particularly of companies who hired the agency to do the type of work you’re interested in.

Passion and adventure

Now this is kind of an x-factor. There are so many ways that you could spin this or adjectives that you could use, but it comes down to how excited the team is to work with you. Engaged and passionate digital agencies are going to produce better work for you than anyone else. They’ll pour their thoughts, their personal research, and their ideas into your project which is what you want in the end. You’re paying for creative minds who have applied these talents to the business world. Look for programmers who contribute to the open-sourced world, look for designers who have a personal website where they try new things, and look for agencies who are passionate about what they do.

How do I find this perfect agency?

Now how do you start your search? I go off of personal recommendations, investigate campaigns or sites that I thought were well done, and I use Google. My personal recommendation is a digital agency called Uber. They started off in London, but have a great office in NYC. Disclosure - I am biased, because I work with them every day, but genuinely everything that comes out of Uber is just top-shelf material for Fortune 500 companies to more medium sized brands to startups alike. They meet all of the criteria which I look for in an agency of record, and have produced some of the best work I’ve seen in the industry.

Did I miss something? What do you look for in a digital agency? How do you start your search? Leave a comment, or squawk at me on Twitter @codelitt

The Most Powerful Countries of the Next Century Will Be Determined in the Next Decade by Technology Access, Freedom of Information, and Ideas

Disclaimer: It’s been awhile since I’ve written on anything worthwhile, but this theory is long in the making. It’s more complex than a few pages, but I try to break it down into something manageable to read.

Power, geopolitical, economic, and democratic success of a country over the next century will not be determined by military power, oil exports, Wall Street, religion, or cash. The most powerful nations of next century will be determined within the next ten years by the technology access, freedom of information, and ideas. This is the dispersion of power which is shifting from centralised points –where we once saw monetary power and military power as the key indicators for success– to a more decentralised model which relies on what experts are calling “soft-power.” This soft power translates into something very real when harnessed, and the steps made over the next decade will echo in the next century as a precedent and foundation for success.

What is power? Power is the ability to make others do what you wish by exerting force of some kind. Power is having influence. Traditionally this force has been in the hands of militaries who threaten lives (the stick), or in the hands of the wealthy who pay for things to be as they wish whether it be through contributions, manipulation, or out-right bribes (the carrot). Soft-power is a different approach. Under this model the force of power is more subtle and a type of downstream engagement where power has a bottom-up effect. The top of which is the international arena. This power is in ideas which others can hear, convert to, and take action upon. The reason for this dispersion of power is overly blatant and obvious– the access to communication, technology, and the free net. Only a few decades ago if a person wanted to simultaneously communicate with all four hemispheres they could; however they had to be extremely wealthy or high up in the military to have access to the technology. Now a 14 year old girl can have millions that have access to her ideas and whom are actively engaged.

People assume that the shift in power will be linear, but history is not linear. History is made by a volatile plot line which has peaks and valleys. Our models for economic power also do not demonstrate the shifting geopolitical climate, elections, shifting policies, and external forces. For example China’s rise to power, if kept on a linear path, will outpace the United States financially in 10 years, and double the US in 20 years. While it is clear that China is rising, the interest of the Chinese government is not to increase it’s citizens’ GDP by a great margin. It is in the best interest of the Chinese centralised government to rise to be the greatest economic power, but not with a well-spread GDP which as history has shown leads to huge shifts in ideologies. The other barrier is their access to information. The Great Firewall of China is China’s worst kept secret. The interesting aspect to look at is the ingenious methods for which the Chinese have figured out how to circumvent this censored internet or post in it. The average Chinese person I’ve met in the last 5 years know’s how to secure VPN access and tunnel out of the Great Firewall. They also use an interesting combinations of onomatopoeias and alliterations so that banned words and phrases don’t get automatically flagged by censorship web-crawlers. Much like the Arab spring, the general populous is growing more restless with these measures and is having more access to new ideas. A decent spark would not be inline with the Chinese economic model as of now and would undoubtedly set them back from this linear path to #1.

This is not to say that China will have to become like the west to rise to power. China is not like the west, and will never be like the west. It is absurdly over-simplified when we in the west think that China’s greatness will be tied to their adoption of western culture and practices. China will rise to power quickly because of their technology access and infrastructure. Not without mention is the Chinese government’s commitment to investing in technology. What will stall them will be their freedom of information. This barrier may be lowered, but we won’t see a large change in this area for at least another 5 years. This will continue to be the Chinese version of a father’s sin. Every super-power comes with their fathers’ sins, and this is undoubtedly China’s. They will continue to pay for this and see the effects echo into the next 25 years.

Access to information and a better educated demographic begets better decision making. The record speaks for itself. The very obvious ones seem more foreign like the recent reelection of Hugo Chavez. Decidedly poor choice given Chavez’s inability to keep his people safe, a widening class gap, devaluation of their currency, and wide-spread crime. Yet even with these facts, the lower-class still voted for Chavez because of no access to free information. Access to television, controlled by Chavez, and state-run newspapers is where the majority of people living in low-income barrios get their information. People in Venezuela with more access to free information (the Internet) and who are monetarily gaining from Chavez decidedly voted for the inspiring opponent, Henrique Capriles. This location and election may seem a bit distant and unrelatable to some though, but the record speaks for the United States as well where low-income families gathering most of their information from the television and radio shows in 2004 reelected George W. Bush who had clearly shown his distaste for lower-class citizens.

So what’s the solution? Clearly dispersion of power makes most governments nervous, but everyone wants to be at the top. We know that the wheels are already in motion, but most governments don’t know what to do. The solution isn’t to fight the power shift, but rather to manage it. If you can manage the power dispersion you get to be involved. Your citizens are going to play this Monopoly game with or without you – I suggest you be the bank. The solution for developing countries to make their mark over the next decade and make a sustainable rise to power is not only to allow access of information to their citizens, but enable their ideas. Ideas and information are the cornerstone, but without the bricks and mortar to build upon these that’s all they’re ever be - a cornerstone that marks what could have been. Developing countries, particularly in Latin America, can harness what is already in the works.

The first step is to eliminate the fear of ideas and change. There are two paths to take. Governments can fear the dispersion of power to the people and fight it. This is likely their first choice, but they won’t win. What everyone should have been talking about with the Arab Spring was not the the change that this had on the region in the Middle East. What we should have been examining is the fact that if this can happen in an area which has been historically plagued in the past 100 with theocracy and dictatorship, then this can happen anywhere. The leap it would take for a Latin American country like Ecuador or Colombia to manage dispersion of power and break historical molds is nothing in comparison for the leap it took for the Arab Spring to happen. Latin American countries historically do have centralised power, but what they do not have hanging around their necks is fear of their government. Latino culture champions controversy and difference in comparison to the Middle East. So instead of fearing and fighting the dispersion of power, these governments should be focusing on embracing it and managing it. Dispersion of power is going to happen. Think of it as splitting up stock options. The percentage that you get at the end may be less, but if these additions increase your valuation then 10% of $1 million is better than 20% of $200K. The winners will be on the side of the aisle who could part with a little power in exchange for a larger pie. The losers will be on the side of the aisle that resisted change. They might have their control, but they will not have real power.

The second step is to put technology into the hands of the people. A government that spends $1 million on purchasing Raspberry Pi has just enabled 30,000 of it’s citizens to put their ideas into action. Gone are the days where ideas needed investment, manufacturing facilities, and powerful friends. Now for the price of $35 you can put a computer in a college student’s hands which they can use to talk about their ideas, read about others’ ideas, and most importantly build their ideas. Spend another $2 million on investment for young companies in your country that are building things that matter to your citizens and improve their quality of life. Then take 10%, only 10%, of your military’s defense budget and begin to allocate it into technology instead of new weapons. Not only will you begin to see young companies blossoming, improve your citizens’ quality of life, and inject cash flow into your economy, but you’ll end up with a better educated public. Some of these young college students are your next soldiers in your military writing code to protect and defend your nation.

The fact of the matter is that the wars that matter will no longer be fought in trenches, in Middle Eastern cities, or in jungles in some far off land. The wars that will be fought that matter will be governments with the smartest technologists, hackers, and makers in the business. Power will no longer be determined by your military strength, because the top military in the world isn’t going anywhere if a 25 year old soldier of your adversary with nothing but a computer just disabled your SATCOMS (satellite communications). If you doubt that this is true, take a look at the Mandiant APT1 report on Chinese Cyber Espionage. Take a look at the tech industries skyrocketing stock prices and 29 year old billionaires. Read the news over the next year and see the percentage of new companies, ideas, and people that are shaking the globe. Then try to come tell me that power doesn’t lie within the technology you place in your citizens’ and in your military’s hands. Power, in every sense of the word, is having influence. The most powerful countries of the next decade will be determined by technology access, freedom of information, and ideas.

Now who will these countries be? Right now it’s up for grabs. The US will not be number one. There are to many stifles to technology enablement, heavily entrenched corruption, and an arrogance that doesn’t allow for change. China? It’s doubtful. While they have all the tools, their in for a rock 5 years once the crescendo of a better educated populous and access to information meet the centralised governments heavy hand. Whenever power shifts, historically we are in for turbulent times. The exciting part of this is that it’s honestly up for grabs. Shifts in power almost certainly mean war, diplomatic contention, and economic turbulence, but the countries that don’t focus their energy in fighting it, but rather managing the power shift will be the ones that come out on top. The west had better get used to the idea of at least 2 Latin American countries coming out in the ring. Mexico, Colombia, and Brazil are all in the running right now, although Chile is making a good effort on investing in technology (albeit unfocused on its own best interest). All the money and military power in the world isn’t going to silence ideas. It will not stop the shift to soft power in the modern world.

Ruby on Rails Launch Page for Multiple User Types - Open-Source

There are quite a few options for one click pre-beta launch pages for the startup world right now. Launchrock is the first example that leaps to mind and they¬† really do an awesome job, but we ran into the problem that we have a two-sided market. Here at Backstagr, we needed a prelaunch page that represented that. Specifically, we needed multiple user types to be able to signup and indicate which user type they were for our records. First of all, we want to be able to deliver them a customised experience when they come back to sign in for that first time, and secondly we want to see the interest level of both sides of the market. Since we couldn’t find a good solution out there that allowed for multiple user types, we did what every good development team (in our humble opinion) should do– we built the tool and released it into the open-source world for anyone to tweak, fix, test, and use.

I’ve completed the back-end server/database (and VERY BASIC front-end) side of things, and over the next couple weeks the talented Mike Babb will be adding the much needed front-end styling and Vicky Jaime will be adding some design. Once we have those two items completed, you’ll be able to see a working example at the Backstagr homepage.

When Mike adds the front-end styling, you’ll probably want to keep the styling, but utilise design assets which match your own brand. Other than that, and a few tweaks to the setup_mailer.rb/database.yml files, you’ll have a working multiple user type launch page for your startup with just an hour of setup. Please feel free to fork the repo on Github, make pull requests, or submit issues. We all have full-time day jobs, so we only get nights and weekends to work on these things, but I’ll do my best to keep up on them. Without further ado, here is the link to the repo!

Follow us on Twitter: @codelitt @mikegbabb @vickyjaime and @backstagr

Creating Ubuntu LiveUSB on a Mac Problem & Solution!

The Ubuntu site has excellent documentation, but I kept running into an error when it came time to mount the image onto the USB so that I could have a LiveUSB ready to go. This slimy error read, “The disk you inserted was not readable by this computer.” It would happen everytime I tried to execute sudo dd if=/path/to/downloaded.img of=/dev/rdiskN bs=1m.

I had quite the search trying to find a simple solution for this. I attempted to mount the image multiple times and nothing seemed to with the USB full partition set as MS-DOS. The fix was quite simple and a small program that does all of the steps for you once you’ve downloaded the OS from the Ubuntu site. Just go to http://penguintosh.com/ for the readme or download the program directly at http://www.mediafire.com/?rctco14mzjayaa9. The program comes with detailed instructions and handles the entire process for you. Let me know if this is of any help!

Follow me on Twitter