tag:gosukiwi.svbtle.com,2014:/feedFederico Ramírez2014-11-18T21:54:02-08:00Federico Ramírezhttps://gosukiwi.svbtle.comSvbtle.comtag:gosukiwi.svbtle.com,2014:Post/i-moved2014-11-18T21:54:02-08:002014-11-18T21:54:02-08:00I Moved!<p>See you at <a href="http://federicoramirez.name/">federicoramirez.name</a>! :)</p>
tag:gosukiwi.svbtle.com,2014:Post/vim-configuration-for-web-development2014-08-21T22:40:03-07:002014-08-21T22:40:03-07:00Using Vim for web development<p>With all the fuss on Atom and Sublime Text, I decided to talk a bit about my favourite editor, <strong>Vim</strong>. I’ve tried both Sublime and Atom, I’ve especially used Sublime for quite some time before comitting to Vim, but ever since I’ve transitioned to Vim I just can’t go back to Sublime or any other non-vim editor. </p>
<p>This is not a post to convince you to use Vim though! Maybe I’ll make one of those one day, for now I’ll just assume you already use Vim and want to use it for web development.</p>
<p>I’m not a Vim veteran but I’ve been using it for quite some time now, and I think my <code class="prettyprint">.vimrc</code> is stable enough to share it. Hopefully this article will help Vim developers out there to improve their workflow a bit, or maybe give Vim a try.</p>
<p>First thing first, <a href="https://gist.github.com/gosukiwi/080d1d3f87f861a15c44">my .vimrc can be found in this gist</a>. It’s divided in 3 parts, the first being essentials and sanitization of defaults, then custom mappings/settings I like, and finally configuration for plugins/themes. Reading the <code class="prettyprint">.vimrc</code> file will be enough to understand the first two sections, nevertheless I’ll highlight some of the features of each part. </p>
<p>The first section is <strong>General Usability</strong> and it tries to make a good base for general file editing, most important settings include using utf8 as the default encoding, unix line-endings, enable syntax highlighting and file type recognition. There are a lot of details in this section and I find it quite hard to remove anything, I find it to be a quite minimal and required configuration for modern text editing.</p>
<p>The next section is more personal, and I called it <strong>Customization</strong>, it has some personal shortcuts I like, for example Windows’ style copy-paste using <code class="prettyprint"><c-c></code> and <code class="prettyprint"><c-v></code>, saving with <code class="prettyprint"><c-s></code>, setting <code class="prettyprint">,</code> as the leader key, indentation and such.</p>
<p>The final part is the <strong>Plugin Configuration</strong>, which I’ll explain in more detail below.</p>
<h1 id="vim-plugins-for-web-development_1">Vim Plugins For Web Development <a class="head_anchor" href="#vim-plugins-for-web-development_1">#</a>
</h1>
<p>The final section of my <code class="prettyprint">.vimrc</code> is plugin configuration. These plugins are my favorites right now for web development, and working without them can be quite a pain!</p>
<h2 id="vundle-a-hrefhttpsgithubcomgmarikvundlevimhtt_2">Vundle - <a href="https://github.com/gmarik/Vundle.vim">https://github.com/gmarik/Vundle.vim</a> <a class="head_anchor" href="#vundle-a-hrefhttpsgithubcomgmarikvundlevimhtt_2">#</a>
</h2>
<p>The now recommended plugin manager for Vim. It works pretty well, and it’s really easy to add and remove plugins. I heard that NeoVim uses a somewhat similar system, so it’s good to have the potential to make a smooth transition.</p>
<h2 id="nerdtree-a-hrefhttpsgithubcomscrooloosenerdtr_2">NERDTree - <a href="https://github.com/scrooloose/nerdtree">https://github.com/scrooloose/nerdtree</a> <a class="head_anchor" href="#nerdtree-a-hrefhttpsgithubcomscrooloosenerdtr_2">#</a>
</h2>
<p>One of the most popular plugins out there, it makes a directory explorer you can navigate using your keyboard to easily access your project’s files. It also allows you to easily create, rename, copy and remove files. I find it quite hard to live without this!</p>
<h2 id="fuzzyfinder-a-hrefhttpsgithubcomvimscriptsfuz_2">FuzzyFinder - <a href="https://github.com/vim-scripts/FuzzyFinder">https://github.com/vim-scripts/FuzzyFinder</a> <a class="head_anchor" href="#fuzzyfinder-a-hrefhttpsgithubcomvimscriptsfuz_2">#</a>
</h2>
<p>Sometimes you want to get quick access to a buffer or a file, for this I use this plugin, with <code class="prettyprint"><leader-b></code> and <code class="prettyprint"><leader-f></code> I can bring a dialog where I can quickly open a buffer that was on the background or open a new file faster than using NERDTree. I use it a lot for buffer swapping.</p>
<h2 id="lightline-a-hrefhttpsgithubcomitchynylightlin_2">Lightline - <a href="https://github.com/itchyny/lightline.vim">https://github.com/itchyny/lightline.vim</a> <a class="head_anchor" href="#lightline-a-hrefhttpsgithubcomitchynylightlin_2">#</a>
</h2>
<p>A pretty status bar for Vim, it has lots of nice information on the current file, no reason no to use this really!</p>
<h2 id="easymotion-a-hrefhttpsgithubcomlokaltogvimeas_2">EasyMotion - <a href="https://github.com/Lokaltog/vim-easymotion">https://github.com/Lokaltog/vim-easymotion</a> <a class="head_anchor" href="#easymotion-a-hrefhttpsgithubcomlokaltogvimeas_2">#</a>
</h2>
<p>Really handy to quickly move though a file, I don’t use it very often as I like to be able to efficiently move the “default” Vim way, but for very long lines or very specific or quick movements it’s awesome, one can get used to this pretty quickly.</p>
<h2 id="surround-a-hrefhttpsgithubcomtpopevimsurround_2">Surround - <a href="https://github.com/tpope/vim-surround">https://github.com/tpope/vim-surround</a> <a class="head_anchor" href="#surround-a-hrefhttpsgithubcomtpopevimsurround_2">#</a>
</h2>
<p>Some goodies for changing surrounds, a pretty neat overall plugin to have. Surprising Vim doesn’t provide something like this by default.</p>
<h2 id="emmet-a-hrefhttpsgithubcommattnemmetvimhttpsg_2">Emmet - <a href="https://github.com/mattn/emmet-vim">https://github.com/mattn/emmet-vim</a> <a class="head_anchor" href="#emmet-a-hrefhttpsgithubcommattnemmetvimhttpsg_2">#</a>
</h2>
<p>This is the first webdev-oriented plugin, it enables you to expand CSS selectors into HTML markup, also known as <strong>Zen Coding</strong>. It really makes writing HTML much more painless.</p>
<h2 id="jshint2-a-hrefhttpsgithubcomshutnikjshint2vim_2">JSHint2 - <a href="https://github.com/Shutnik/jshint2.vim">https://github.com/Shutnik/jshint2.vim</a> <a class="head_anchor" href="#jshint2-a-hrefhttpsgithubcomshutnikjshint2vim_2">#</a>
</h2>
<p>This one is also webdev-oriented, it’s used to perform JSHint validation on Javascript files. I configured it to run every time a <code class="prettyprint">*.js</code> file is saved. Something similar could be archieved with something like Gulp or Grunt but I like the integrated solution.</p>
<h2 id="css-color-a-hrefhttpsgithubcomskammervimcssco_2">CSS Color - <a href="https://github.com/skammer/vim-css-color">https://github.com/skammer/vim-css-color</a> <a class="head_anchor" href="#css-color-a-hrefhttpsgithubcomskammervimcssco_2">#</a>
</h2>
<p>Another webdev-oriented plugin, this one allows you to see a little preview of the colors specified in the CSS file, for LESS and SASS it might not be a big deal but it’s a nice little feature to have. Quite optional.</p>
<h2 id="syntax-support_2">Syntax Support <a class="head_anchor" href="#syntax-support_2">#</a>
</h2>
<p>Vim doesn’t ship with support for every file type, and as a web developer we work with a lot of different languages and syntaxes, so I included what I needed, which for now is syntax support for <a href="https://github.com/hail2u/vim-css3-syntax">CSS3</a>, <a href="https://github.com/kchmck/vim-coffee-script">CoffeeScript</a>, <a href="https://github.com/groenewege/vim-less">LESS</a>/<a href="https://github.com/tpope/vim-haml">SASS</a> and <a href="https://github.com/digitaltoad/vim-jade">Jade</a>. This also is quite personal but I’m sure CSS3 and LESS/SASS will be a pretty good addition in general.</p>
<h1 id="conclusion_1">Conclusion <a class="head_anchor" href="#conclusion_1">#</a>
</h1>
<p>So that’s my <code class="prettyprint">.vimrc</code>. It works nicely for me and I’m pretty happy with it. I’d love to know yours, and your opinion on mine and my plugins. Cheers! </p>
tag:gosukiwi.svbtle.com,2014:Post/highperformance-wordpress-installation-using-nginx-mariadb-and-hhvm-from-scratch-in-ubuntu-13102014-07-24T10:31:22-07:002014-07-24T10:31:22-07:00High-performance WordPress installation using Nginx, MariaDB and HHVM from scratch in Ubuntu 13.10<p>Not so recently I released my studio website which uses WordPress, so I had to set up a web server from scratch, I found this a good oportunity to write something helping people easily set up a high performance WordPress using the latest mainstream technology, hopefully you find this article helpful :)</p>
<h1 id="step-1-setting-up_1">Step 1: Setting up <a class="head_anchor" href="#step-1-setting-up_1">#</a>
</h1>
<p>So you just created a new droplet, a shining Ubuntu 13.10 installation, you ssh’d into<br>
it and are presented with a lovely virgin terminal. First things first! Update and upgrade<br>
all installed packages</p>
<pre><code class="prettyprint">$ apt-get update && apt-get upgrade
</code></pre>
<p>After a few moments the command will finish and we’re ready to install all our software.<br>
The next thing to do is creating a user so we don’t use <code class="prettyprint">root</code> as it’s a very bad practice!</p>
<pre><code class="prettyprint">$ useradd deploy
</code></pre>
<p>We named our new user <code class="prettyprint">deploy</code> you should name it whatever you want, just remember to make<br>
the appropiate changes. Once we have our new user let’s create a home directory for it!</p>
<pre><code class="prettyprint">$ mkdir /home/deploy
$ chown deploy:deploy /home/deploy -R
</code></pre>
<p>We created a new directory for our user and add it as owner so she can freely work inside<br>
her home directory. </p>
<p>Finally let’s create a password for our <code class="prettyprint">deploy</code> user</p>
<pre><code class="prettyprint">$ passwd deploy
</code></pre>
<p>Use any password you want, it will be used for sudo commands as well as logging in though<br>
ssh (if you follow the optional step we’ll use SSH keys to log in instead of the unsafe<br>
passwords! but that step is optional).</p>
<p>Let’s configure the users who can use <code class="prettyprint">sudo</code></p>
<pre><code class="prettyprint">$ visudo
</code></pre>
<p>Comment all existing grant lines and add the following at the end of the file</p>
<pre><code class="prettyprint">root ALL=(ALL) ALL
deploy ALL=(ALL) ALL
</code></pre>
<p>Save and exit. Now only <code class="prettyprint">root</code> and <code class="prettyprint">deploy</code> can use sudo. Another change we should make<br>
now is disallow root login though ssh, for this edit the <code class="prettyprint">/etc/ssh/sshd_config</code> file and<br>
add the following at the end</p>
<pre><code class="prettyprint">PermitRootLogin no
</code></pre>
<p>Finally restart the ssh service so it loads the changes</p>
<pre><code class="prettyprint">$ service ssh restart
</code></pre>
<p>So far so good! Let’s log out <code class="prettyprint">root</code> and ssh as <code class="prettyprint">deploy</code> instead, from now on we’ll work <br>
with that user.</p>
<p>Let’s secure our server a bit</p>
<pre><code class="prettyprint">$ sudo apt-get install fail2ban
</code></pre>
<p>Fail2ban is an app which bans a certain IP from logging into your server if it has failed<br>
the password too many times, it comes with nice defaults so that will do.</p>
<p>Another thing we have to do is enable the firewall, this is easy</p>
<pre><code class="prettyprint">$ sudo ufw allow 22
$ sudo ufw allow 80
$ sudo ufw allow 443
$ sudo ufw enable
</code></pre>
<p>We only allow the ports for ssh (22) and nginx (80 and 443 if https).</p>
<h1 id="step-15-public-key-authentication_1">Step 1.5: Public key authentication <a class="head_anchor" href="#step-15-public-key-authentication_1">#</a>
</h1>
<p>If you want to secure your server a bit more we can require all ssh sessions to <br>
authenticate using a public key instead of a password, this is considerably safer.</p>
<p>First step is creating a <code class="prettyprint">~/.ssh/authorized_keys</code> file and pasting your public key <br>
(most likely id_rsa.pub) there.</p>
<pre><code class="prettyprint">$ mkdir ~/.ssh
$ vim ~/.ssh/authorized_keys
</code></pre>
<p>Once you have saved your public key there let’s change the permissions of that file</p>
<pre><code class="prettyprint">$ chmod 400 ~/.ssh/authorized_keys
</code></pre>
<p>Now try ssh-ing as <code class="prettyprint">deploy</code>, you should be able to log in without typing the root<br>
password (your public key might require a password, that’s up to you).</p>
<p>The final step is to require ssh to authenticate only with public keys, edit <code class="prettyprint">/etc/ssh/sshd_config</code> once again and append this line:</p>
<pre><code class="prettyprint">PasswordAuthentication no
</code></pre>
<p>Finally restart ssh</p>
<pre><code class="prettyprint">$ sudo service ssh restart
</code></pre>
<p>That’s it!</p>
<h1 id="step-2-setting-up-the-webserver_1">Step 2: Setting up the webserver <a class="head_anchor" href="#step-2-setting-up-the-webserver_1">#</a>
</h1>
<p>We’ll use Nginx as our webserver, thankfully setting it up is quite easy! </p>
<pre><code class="prettyprint">$ sudo apt-get install nginx
</code></pre>
<p>That was fast. Let’s move onto MariaDB, because Ubuntu doesn’t include a package for MariaDB we have to manually add a package repository so we can easily install it with <code class="prettyprint">apt-get</code>:</p>
<pre><code class="prettyprint">$ sudo apt-get install software-properties-common
$ sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xcbcb082a1bb943db
$ sudo add-apt-repository 'deb http://download.nus.edu.sg/mirror/mariadb/repo/10.0/ubuntu saucy main'
</code></pre>
<p>Note: If you are not running Ubuntu 13.10 you can see what package repository to use <a href="https://downloads.mariadb.org/mariadb/repositories/#mirror=nus&distro=Ubuntu&distro_release=saucy&version=10.0">in MariaDB official docs</a>.</p>
<p>We can now install MariaDB as follows</p>
<pre><code class="prettyprint">$ sudo apt-get update
$ sudo apt-get install mariadb-server
</code></pre>
<p>It will prompt us for a password, choose a password for your MariaDB root user and <br>
continue, the installation is pretty quick. Once it ends, let’s secure it running</p>
<pre><code class="prettyprint">$ mysql_secure_installation
</code></pre>
<p>It will prompt us quite a lot of questions, if you don’t want to change the root<br>
password answer <code class="prettyprint">No</code> to the first one, the rest are <code class="prettyprint">Yes</code>.</p>
<p>Finally let’s install <code class="prettyprint">HHVM</code>, Facebook’s PHP interpreter. Because HHVM uses JIT <br>
compilation code execution is quite fast, together with Nginx we’ll make WordPress fly!</p>
<p>Here we have the same issue as with MariaDB, let’s add the custom package repository:</p>
<pre><code class="prettyprint">$ wget -O - http://dl.hhvm.com/conf/hhvm.gpg.key | sudo apt-key add -
$ echo deb http://dl.hhvm.com/ubuntu saucy main | sudo tee /etc/apt/sources.list.d/hhvm.list
</code></pre>
<p>Now install it</p>
<pre><code class="prettyprint">$ sudo apt-get update
$ sudo apt-get install hhvm
</code></pre>
<p>That will install HHVM in our server, there is one final step, we have to configure HHVM to work with Nginx, luckly this is super easy!</p>
<pre><code class="prettyprint">$ sudo /usr/share/hhvm/install_fastcgi.sh
</code></pre>
<p>Let’s try it out</p>
<pre><code class="prettyprint">$ sudo echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/phpinfo.php
</code></pre>
<p>If you navigate to <code class="prettyprint">http://yourip/phpinfo.php</code> you should see a little message saying<br>
“HHVM”. Success!</p>
<h1 id="step-3-installing-wordpress_1">Step 3: Installing WordPress <a class="head_anchor" href="#step-3-installing-wordpress_1">#</a>
</h1>
<p>Let’s install WordPress, to make it easy I’ll make a soft link to the nginx public <br>
folder and set <code class="prettyprint">deploy</code> as owner</p>
<pre><code class="prettyprint">$ sudo ln -s /usr/share/nginx/html ~/www
$ sudo chown deploy:deploy /usr/share/nginx/html -R
</code></pre>
<p>We can now just work inside <code class="prettyprint">~/www</code></p>
<pre><code class="prettyprint">$ cd ~/www
$ wget http://wordpress.org/latest.tar.gz
$ tar -xvzf wordpress.3.x.x.tar.gz
$ mv wordpress/* .
$ rm -rf wordpress
$ rm wordpress.3.x.x.tar.gz
</code></pre>
<p>The above code will download wordpress, extract it into <code class="prettyprint">wordpress/</code> and move the<br>
contents to that folder to our www root, finally it removes the empty wordpress folder<br>
as well as the .tar.gz file.</p>
<p>If you navigate to your site index you’ll be prompted to install WordPress, let’s first<br>
create a database</p>
<pre><code class="prettyprint">$ mysql -u root -p
</code></pre>
<p>MariaDB will ask for your root password, once you enter it we can create a new database</p>
<pre><code class="prettyprint">$ CREATE DATABASE wordpress;
</code></pre>
<p>That’s it! We have our database, I named it <code class="prettyprint">wordpress</code> but you can choose any name you<br>
want. Finally exit the SQL prompt</p>
<pre><code class="prettyprint">$ exit
</code></pre>
<p>Now proceed with wordpress installation, use <code class="prettyprint">wordpress</code> for the database, <code class="prettyprint">localhost</code><br>
for host, <code class="prettyprint">root</code> for user and the password you chose when installing MariaDB.</p>
<p>Good! We now have a fully functional WordPress running on Nginx + MariaDB + HHVM!</p>
<h1 id="step-4-installing-sendmail_1">Step 4: Installing sendmail <a class="head_anchor" href="#step-4-installing-sendmail_1">#</a>
</h1>
<p>To be able to send mails though our server we need to install a MTA, postfix beeing the<br>
simplest option.</p>
<pre><code class="prettyprint">$ sudo apt-get install sendmail
$ sudo sendmailconfig
</code></pre>
<p>Just accept everything the configuration asks, it has pretty good defaults. To test<br>
your sendmail installation you can run</p>
<pre><code class="prettyprint">$ echo "Hello!" | sendmail myemail@gmail.com
</code></pre>
<p>If it takes like a minute to send, you have to configure your IPv4 hostname</p>
<pre><code class="prettyprint">$ sudo vim /etc/hosts
</code></pre>
<p>And add the following line</p>
<pre><code class="prettyprint">127.0.0.1 localhost.localdomain localhost HOST_NAME
</code></pre>
<p><code class="prettyprint">HOST_NAME</code> is the value the command <code class="prettyprint">hostname</code> returns.</p>
<p>If you have a domain you can replace the code above with</p>
<pre><code class="prettyprint">127.0.0.1 mail.mydomain.com mydomain.com HOST_NAME
</code></pre>
<p>Restart sendmail and try again</p>
<pre><code class="prettyprint">$ sudo service sendmail restart
$ echo "Hello!" | sendmail myemail@gmail.com
</code></pre>
<p>It should now work pretty quickly!</p>
<h1 id="step-5-optimization_1">Step 5: Optimization <a class="head_anchor" href="#step-5-optimization_1">#</a>
</h1>
<p>Let’s start optimizing! First lets make Nginx cache our static assets as well as gzip <br>
js and css files. To do this let’s update the global nginx configuration file</p>
<pre><code class="prettyprint">$ sudo vim /etc/nginx/nginx.conf
</code></pre>
<p>The gzip section must look like this</p>
<pre><code class="prettyprint">##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
</code></pre>
<p>We’ll gzip css, json, js and xml files.</p>
<p>Let’s now add expiration time on our assets so browsers cache them, for this we’ll<br>
update the per-site configuration file</p>
<pre><code class="prettyprint">$ sudo vim /etc/nginx/sites-available/default
</code></pre>
<p>Add the following definition inside <code class="prettyprint">server { }</code></p>
<pre><code class="prettyprint">location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff|ttf|svg|otf)$ {
expires 30d;
add_header Pragma public;
add_header Cache-Control "public";
}
</code></pre>
<p>We now have proper headers to our static assets so browsers can cache them! </p>
<h2 id="wordpress-cache_2">WordPress Cache <a class="head_anchor" href="#wordpress-cache_2">#</a>
</h2>
<p>Another thing we can do to improve performance is using <a href="https://wordpress.org/plugins/w3-total-cache/">W3 Total Cache</a>. Download it, install it and enable it.</p>
<p>This plugin offers several options, we’ll just use <strong>Page Cache</strong> and set it to <br>
<strong>Disk(Enhanced)</strong>.</p>
<p>We now have to properly update our nginx site configuration</p>
<pre><code class="prettyprint">$ vim /etc/nginx/sites-available/default
</code></pre>
<p>And make the following changes</p>
<pre><code class="prettyprint">server {
# ...
set $cache_uri $request_uri;
# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
set $cache_uri 'null cache';
}
if ($query_string != "") {
set $cache_uri 'null cache';
}
# Don't cache uris containing the following segments
if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail ).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations .php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
set $cache_uri 'null cache';
}
# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
set $cache_uri 'null cache';
}
# Use cached or actual file if they exists, otherwise pass request to WordPress
location / {
try_files /wp-content/cache/page_enhanced/${host}${cache_uri}_index.html $uri $uri/ /index.php?$args;
}
# ...
}
</code></pre>
<h2 id="pretty-urls_2">Pretty URLs <a class="head_anchor" href="#pretty-urls_2">#</a>
</h2>
<p>One final thing to do is make WordPress permalinks play nice with Nginx, normally <br>
WordPress appends <code class="prettyprint">/index.php/myLink</code> for all links when using nginx pretty urls, to fix<br>
this we can use <a href="https://rtcamp.com/nginx-helper/">Nginx Helper Plugin</a>, simply download<br>
the plugin, install it, enable it, and that’s it! We now have pretty URLs.</p>
<p>If <strong>you didn’t install W3 Total Cache</strong> in the previous step, add this to your <br>
<code class="prettyprint">/etc/nginx/sites-available/default</code> site configuration</p>
<pre><code class="prettyprint"># Use cached or actual file if they exists, otherwise pass request to WordPress
location / {
try_files $uri $uri/ /index.php?$args;
}
</code></pre>
<p>Have fun with your WordPress on steroids installation!</p>
tag:gosukiwi.svbtle.com,2014:Post/object-oriented-javascript2014-05-23T07:31:55-07:002014-05-23T07:31:55-07:00Object Oriented Javascript<p>If you are reading this I’d like to assume you know what Javascript is and the fact that it’s object oriented, what not many people know though is how to do the most common object oriented “things” in Javascript, such as inheritance, private functions and such. </p>
<p>The fact that Javascript is <strong>prototype</strong> based and not <strong>class</strong> based is what makes it hard to get into for most programmers. If you come from Java, PHP, C#, C++, Python, Ruby or pretty much any language you’ll find objects in Javascript are a bit unique, and they certainly are but in a good way!</p>
<h1 id="prototypes_1">Prototypes <a class="head_anchor" href="#prototypes_1">#</a>
</h1>
<p>Let’s talk a little bit about prototypes first. What are prototypes? The concept is really simple in fact, whenever you ask an attribute to an object, it will look for that attribute in itself, and if it cannot find it, it will look for it in a special hidden attribute called prototype (which is also just an object), if it’s there it will return it, if not it will just return <code class="prettyprint">undefined</code>. </p>
<p>There is a catch though, you can access the prototype attribute of <strong>functions</strong>! So you cannot do <code class="prettyprint">{}.prototype</code> but you can do <code class="prettyprint">Object.prototype</code>! That’s because <code class="prettyprint">Object</code> is actually a function, we’ll talk more about that in the following sections.</p>
<h1 id="constructor-functions_1">Constructor Functions <a class="head_anchor" href="#constructor-functions_1">#</a>
</h1>
<p>As you might know a constructor is a function which gets called every time a new object is created, it’s used to initialize the new object.</p>
<p>Because Javascript has no classes the <code class="prettyprint">new</code> keyword works on <strong>functions</strong> not classes, inside this function you can use the <code class="prettyprint">this</code> keyword and it will point to your new object, for example:</p>
<pre><code class="prettyprint">function Person(name) {
this.name = name;
}
</code></pre>
<p>We can now create a person</p>
<pre><code class="prettyprint">var person = new Person("Thomas O'Malley");
console.log(person.name); // logs "Thomas O'Malley"
</code></pre>
<p>The function <code class="prettyprint">Person</code> is called a <strong>constructor function</strong> and it starts with a capital letter. It’s <strong>super</strong> important to start all your constructor functions with a capital letter, not only it’s a convention, but if you call that function without the <code class="prettyprint">new</code> keyword you’ll get unexpected results! Inside the constructor function <code class="prettyprint">this</code> now points to the <code class="prettyprint">Window</code> global object, and doesn’t return anything unless you say so. This is one of the most criticized features of Javascript, the inconsistency of the <code class="prettyprint">this</code> keyword.</p>
<p>If you start all your constructor functions with a capital letter you’ll know just by looking that it must be used with <code class="prettyprint">new</code>. Another option is to avoid the usage of the <code class="prettyprint">new</code> keyword whenever possible:</p>
<pre><code class="prettyprint">function person(name) {
return {
name: name
};
}
</code></pre>
<p>This function also returns a new object. Which way to program is up to you, normally constructor functions is the only use case when using <code class="prettyprint">new</code> is good, Douglas Crockford talks a bit about this <a href="http://yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya/">in this YUI blog post</a>.</p>
<h2 id="a-little-more-about-the-new-keyword_2">A little more about the new keyword <a class="head_anchor" href="#a-little-more-about-the-new-keyword_2">#</a>
</h2>
<p>Feel free to skip this little section, but I’d like to talk a bit about this keyword.</p>
<p>The <code class="prettyprint">new</code> keyword creates a new empty object with our constructor function in the hidden prototype attribute, it then executes our function and binds <code class="prettyprint">this</code> to the newly created object, finally it returns that object or if there’s a <code class="prettyprint">return</code> statement, the value of that statement. MDN explains these steps nicely as follows</p>
<ol>
<li>A new object is created, inheriting from foo.prototype.</li>
<li>The constructor function foo is called with the specified arguments and this bound to the newly created object. new foo is equivalent to new foo(), i.e. if no argument list is specified, foo is called without arguments.</li>
<li>The object returned by the constructor function becomes the result of the whole new expression. If the constructor function doesn’t explicitly return an object, the object created in step 1 is used instead. (Normally constructors don’t return a value, but they can choose to do so if they want to override the normal object creation process.)</li>
</ol>
<p>If you are interested you should check out <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new">the full article on MDN</a>.</p>
<h1 id="encapsulation_1">Encapsulation <a class="head_anchor" href="#encapsulation_1">#</a>
</h1>
<p>One of the things that object oriented code allows you to do is hide certain functionality from the consumer, meaning you are able to keep an internal state for your object which is not needed for the consumer to know, this is sometimes referred as “black box” or Encapsulation.</p>
<p>Encapsulation is good, and it’s easy to implement in Javascript! Let’s see how</p>
<pre><code class="prettyprint">function Person(name) {
var _name = name;
return {
name: function (name) {
if(!name) {
return _name;
}
_name = name;
}
};
}
</code></pre>
<p>Here we have a constructor function which returns an object, so that’s what the <code class="prettyprint">new</code> keyword will return. That object uses a variable from inside the constructor function’s scope, which cannot be accessed from outside our new object! </p>
<pre><code class="prettyprint">function Person(name) {
// our code from before...
}
var person = new Person('Mike');
console.log(person.name()); // "Mike"
person.name('John');
console.log(person.name()); // "John"
console.log(person._name); // undefined
console.log(_name); // undefined
</code></pre>
<p>What we just did is called a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures">closure</a> and they are used quite a lot in Javascript, it might seem hard to understand and use but it’s really handy once you get used to them!</p>
<h1 id="inheritance_1">Inheritance <a class="head_anchor" href="#inheritance_1">#</a>
</h1>
<p>One of object oriented programming most important concepts is inheritance, meaning an object an inherit all the properties and methods from another parent object, and then add specific functionality on their own.</p>
<p>It’s a bit tricky but we can do it in Javascript with no major hassle, the idea is to use the <strong>prototype</strong> attribute to hold our base (a.k.a parent) object, so we can easily override / overload them if needed.</p>
<pre><code class="prettyprint">function Weapon(name) {
this.name = name;
}
function Sword() {
this.damage = 12;
this.attack = function () {
return 'Attack with ' + this.name;
};
}
Sword.prototype = new Weapon('Sword');
var sword = new Sword();
console.log(sword.name); // 'Sword'
console.log(sword.damage); // 12
console.log(sword.attack()); // Attack with Sword
</code></pre>
<p>Because we can access the <strong>prototype</strong> attribute when working with functions we simply create a constructor function and then add an object to it’s prototype.</p>
<p>Another alternative would be just copying the attributes from the parent object to the child if the child doesn’t already have them, personally I find the first solution more elegant, but sometimes the latter is just a better fit, a good use case is when working with objects instead of constructor functions. See for example <a href="http://api.jquery.com/jquery.extend/">jQuery’s extend</a>.</p>
<h2 id="a-note-on-prototypes_2">A note on prototypes <a class="head_anchor" href="#a-note-on-prototypes_2">#</a>
</h2>
<p>When we use <code class="prettyprint">new</code> to create a new object it copies the prototype onto the new object, meaning primitive values get copied by value, but objects are copied <strong>by reference</strong>, so for function definitions we should always write <code class="prettyprint">Constructor.prototype.myFunction</code>. Here’s a simple demonstration of this concept</p>
<pre><code class="prettyprint">function a () { this.f = function () {} }
a.prototype.F = function () {}
var o1 = new a();
var o2 = new a();
o1.f === o2.f // false
o1.F === o2.F // true
</code></pre>
<h1 id="static-vs-instance_1">Static vs Instance <a class="head_anchor" href="#static-vs-instance_1">#</a>
</h1>
<p>In the example above, for each Sword object we created the prototype Weapon object was copied, meaning each sword had it’s own copy of Weapon; There’s one copy per <strong>instance</strong>.</p>
<p>Sometimes you want to make a static attribute, meaning it’s shared across all instances, this is useful for sharing methods and data instead of copying them over and over. To create static attributes we use the constructor function. </p>
<p>The <code class="prettyprint">new</code> keyword only copies the prototype of the constructor function, if we add any regular property it won’t be there in the new object, but we can easily access it later on, as we see here</p>
<pre><code class="prettyprint">function Counter(name) {
this.add = function () {
console.log(++Counter.counter);
};
}
Counter.counter = 0;
var counter = new Counter();
counter.add(); // 1
counter.add(); // 2
counter.add(); // 3
var counter2 = new Counter();
counter2.add(); // 4
</code></pre>
<h1 id="abstracting-it-up-a-bit_1">Abstracting it up a bit <a class="head_anchor" href="#abstracting-it-up-a-bit_1">#</a>
</h1>
<p>A lot of libraries already provide a bunch of helper methods to easily get away with this, abstracting quite a lot of complexity, for example, in <a href="http://canjs.com/">CanJS</a> you create a model constructor function as follows</p>
<pre><code class="prettyprint">var MyModel = can.Model.extend({
/* static props */
},
{
/* instance props */
});
var myModel = new MyModel();
</code></pre>
<p>Most libraries create an <code class="prettyprint">extend</code> function in their objects which simplifies the inheritance process, this method normally either uses the prototype attribute or just overrides an object properties. For instance, take a look at <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">this MDN article on Object.create</a> and John Resig’s <a href="http://ejohn.org/blog/simple-javascript-inheritance/">Simple Javascript Inheritance</a> article.</p>
<p>There are a lot of abstractions, but knowing how to do them “by hand” is quite important to fully understand your code! There is no knowledge that is not power ;)</p>
<h1 id="conclusion_1">Conclusion <a class="head_anchor" href="#conclusion_1">#</a>
</h1>
<p>All in all OOP in Javascript is possible and not that hard to archieve, it surely is different though! </p>
<p>What I love about Javascript is that it’s such a simple language, you can do OOP as well as functional programming, or even mix both! In Javascript, that’s up to you.</p>
<p>I hope you find it useful and I’d like to hear your suggestions!</p>
<p>Cheers!</p>
tag:gosukiwi.svbtle.com,2014:Post/how-to-get-a-php-devenv-in-no-time2014-05-14T23:41:55-07:002014-05-14T23:41:55-07:00How to get an awesome PHP DevEnv in no time with Nitrous and Vim<p>I’ve been playing around with PHP development environments for quite some time now, and I’d like to share the last setup I’m working on, which I find quite portable and just plain awesome. This will not be an in-depth tutorial of all the technologies I use, I will just summarize how I got there and how you can get started if you want to. Below you can see the environment I’m talking about.</p>
<p><a href="https://svbtleusercontent.com/7x6f6hc8sbofaw.png"><img src="https://svbtleusercontent.com/7x6f6hc8sbofaw_small.png" alt="devenv.png"></a></p>
<p>I’ll detail each piece in the following section but if you take a look at the picture you’ll notice several things on your own, the first thing you might notice is I’m using Windows 8, which might seem lame for a PHP developer, I have my reasons for that but when developing I <strong>need</strong> to use an UNIX terminal, that’s why I use <strong>Nitrous</strong> and connect over SSH.</p>
<p>If you use <strong>Vim</strong> you’ll notice I’m using that lovely editor in console mode, I’ve blogged before about Vim as it’s by far my favourite text editor.</p>
<p>Finally I use <strong>tmux</strong>, which you might not notice unless you are quite used to the UNIX universe and paying attention to the screenshot. Tmux is a terminal multiplexer and it comes already installed on Nitrous VM, so there’s no reason not to use it! </p>
<h1 id="nitrous_1">Nitrous <a class="head_anchor" href="#nitrous_1">#</a>
</h1>
<p><a href="https://www.nitrous.io/">Nitrous</a> is quite an awesome and <strong>free</strong> service which gives you a VM running Ubuntu for your development needs, you can access it anywhere as long as you have a working Internet connection. You can also install whatever you want! So even if you createad your VM as a “Python VM” you can install Ruby and work with Rails, or Node! (see <a href="http://help.nitrous.io/autoparts/">autoparts</a>)</p>
<p>If you don’t want to use ssh you can go on and use the Online IDE they have (which has a Vim mode by the way), or you can download <a href="https://www.nitrous.io/desktop">Nitrous Desktop</a> and share a folder with your VM, that way you can use Sublime Text or any other editor of choice! The folder will be synced to the server every time you make a change.</p>
<p>The advantage using ssh has over only the desktop app is that synchronization takes some seconds (sometimes it can get a bit slow, like 10+ seconds), and after that you still have to wait some more seconds to refresh your browser so all in all it gets tedious pretty fast. If you use ssh all changes are saved instantaneously so you can just hit refresh and see your changes.</p>
<p>The downside though is that you need to use a text editor which works on the terminal, and you might not like Vim. It can also be harder to set up and get started, as you might need to learn some stuff, but once you get going it really pays off!</p>
<h1 id="vim_1">Vim <a class="head_anchor" href="#vim_1">#</a>
</h1>
<p>Vim is an old-school text editor which works in the terminal as well as it’s own window. Don’t get discouraged because it’s old though, it’s used pretty actively and there’s a <a href="http://neovim.org/">new “version” coming up</a>. It’s quite hard to get started with Vim but it really pays off once you get used to it! Vim is an essential part in this environment as you cannot run many other editors in the terminal.</p>
<p>If you want to get started with Vim then <a href="http://www.amazon.com/Practical-Vim-Thought-Pragmatic-Programmers/dp/1934356980">Practical Vim</a> is the definitive guide, you’ll learn lots of useful use cases for Vim and be on a good path to learn more on your own.</p>
<p>If you decide to use Vim for this setup you can upload your <code class="prettyprint">.vimrc</code> file and <code class="prettyprint">.vim/</code> folder to your VM’s user folder <code class="prettyprint">~/</code> so you can use your Vim settings!</p>
<h1 id="tmux_1">tmux <a class="head_anchor" href="#tmux_1">#</a>
</h1>
<p>Everyone’s favorite terminal multiplexer, the website describes it as follows</p>
<blockquote>
<p>[A terminal multiplexer] lets you switch easily between several programs in one terminal, detach them (they keep running in the background) and reattach them to a different terminal. And do a lot more.</p>
</blockquote>
<p>Well tmux does indeed quite a lot more! I just use a little horizontal window at the bottom to run PHP commands, some people like that window as a vertical window on the right of the screen, that’s up to you really. </p>
<p>Using tmux is optional but it has quite a lot of advantages so consider using it! If you’ve never used tmux before <a href="http://www.sitepoint.com/tmux-a-simple-start/">here’s a nice guide to get started</a>.</p>
<h1 id="conclusion_1">Conclusion <a class="head_anchor" href="#conclusion_1">#</a>
</h1>
<p>The steps for a quick and awesome PHP development environment are</p>
<ol>
<li>Get a Nitrous account and create a PHP box</li>
<li>Download Nitrous Desktop and forward the ports your VM exposes</li>
<li>Upload your Vim configuration to your VM’s root folder</li>
<li>Connect over SSH and use tmux to secure your session in case of connection loss</li>
<li>Navigate to <code class="prettyprint">http://localhost:3000</code> and get to work!</li>
</ol>
<p>You end up with a nice environment you can easily replicate on other computers, everything is synced to the could in case something happens, you can easily see your app on “localhost”, you get to work in with nice UNIX terminal multiplexer thanks to tmux and all you need to do is install the Nitrous desktop app!</p>
<p>You can even skip the Nitrous app part and just work with ssh but you wont get a local copy of your apps and might have to configure ssh manually, also you won’t get a nice port redirection to work on “localhost”.</p>
<p>All in all I really like this setup, and I hope some people find it useful too, I’d love to hear your opinions on this and how it can improve! Cheers!</p>
tag:gosukiwi.svbtle.com,2014:Post/the-right-way-of-caching-ajax-requests-with-jquery2014-05-08T20:23:20-07:002014-05-08T20:23:20-07:00The right way of caching AJAX requests with jQuery<p>AJAX is everywhere and jQuery offers a nice simple API to easily create AJAX requests, what not many people know though, is that it also provides ways to ease the burden of callback hell which accompanies asynchronous code! It does so by giving us <strong>promises</strong>. </p>
<p>What’s a promise? It’s just an object with a given task which makes a <strong>promise</strong> to us that it will eventually resolve that task, and tell us either it succeeded or failed. This might seem silly but it’s actually quite useful.</p>
<p>In this article I’ll show how to use promises to cache AJAX requests in a clean and elegant way.</p>
<p>First, let’s make a good ‘ol AJAX call using jQuery to retrieve information from a song.</p>
<pre><code class="prettyprint">// Load a song information
$.post('/songs', { id: 1 }, function(response) {
console.log(response);
});
</code></pre>
<p>So far, so good, now imagine I make several calls to that AJAX function, it makes sense to create a more generic function to wrap my repeated functionality</p>
<pre><code class="prettyprint">function loadSong(songId, callback) {
$.post('/songs', { id: songId }, callback);
}
</code></pre>
<p>Now I can call </p>
<pre><code class="prettyprint">loadSong(1, function (response) { /* do something */ }
loadSong(2, function (response) { /* do something */ }
loadSong(3 function (response) { /* do something */ }
</code></pre>
<p>But I have generated a callback along the way, let’s get rid of it, assuming we just want to show the contents of the song, we can make a function for that</p>
<pre><code class="prettyprint">function showSong(response) {
/* Show the song in the DOM somehow */
}
</code></pre>
<p>I can now do</p>
<pre><code class="prettyprint">loadSong(1, showSong);
loadSong(2, showSong);
</code></pre>
<p>Now I notice that I send a request to get the song with <code class="prettyprint">id</code> 1 several times, I’d like to cache the response so I only send it once, one solution would be</p>
<pre><code class="prettyprint">var cache = {};
function loadSong(id, callback) {
if(!cache[id] !== null) {
callback(cache[id]);
return;
}
if(cache[id] === null) {
return;
}
cache[id] = null;
$.post('/songs', { id: id }, function (data) {
cache[id] = data;
callback(cache[id]);
});
}
</code></pre>
<p>Now we have a cache, initially I set the cache to <code class="prettyprint">null</code> and don’t change it to an object until the AJAX success callback has been executed, if the cache is null I know I’m waiting for an AJAX call to resolve.</p>
<p>This solution works but it’s repetitive and quite ugly, there’s a better way, with promises! Turns out jQuery AJAX functions already return a promise, as stated before promises are just objects will eventually be resolved. How do we know if it’s resolved? We just pass a callback to the <code class="prettyprint">done</code> function! For example</p>
<pre><code class="prettyprint">var deferred = $.post('/songs', { id: 1 });
deferred.done(callback);
</code></pre>
<p>Notice that I named the variable <code class="prettyprint">deferred</code>, this is because it’s actually a <code class="prettyprint">deferred</code> object which is a superset of promises, according to jQuery’s official docs</p>
<blockquote>
<p>The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, and state), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).</p>
</blockquote>
<pre><code class="prettyprint">var promise = $.post('/songs', { id: 1 }).promise();
promise.done(callback);
</code></pre>
<p>It’s safer to work with promises when we don’t need to update the state. A nice thing about promises is that if we call <code class="prettyprint">done</code> once the promise has been resolved, the callback is called instantly! Knowins this we can rewrite our little cache as follows</p>
<pre><code class="prettyprint">var cache = {};
function loadSong(id, callback) {
if(!cache[id]) {
cache[id] = $.post('/songs', { 'id': id }).promise();
}
cache[id].done(callback);
}
</code></pre>
<p>Now that’s much cleaner!</p>
<h1 id="bonus-example_1">Bonus Example <a class="head_anchor" href="#bonus-example_1">#</a>
</h1>
<p>Another awesome way to use Deferred is to load chained AJAX request. Assume we want to load several songs at once, and we have to wait to get all songs before doing the rendering, with regular callbacks this is <strong>hell</strong>! You have to chain AJAX calls inside callbacks and such!</p>
<pre><code class="prettyprint">$.post('/song', { id: 1 }, function (song1) {
$.post('/song', { id: 2 }, function (song2) {
$.post('/song', { id: 3 }, function (song3) {
drawToDOM(song1, song2, song3);
}
});
});
</code></pre>
<p><strong>EW!</strong> that codei s ugly, we could create functions for each callback but we’ll end up with a lot of spaghetti code anyways! </p>
<p>Deferred to the rescue! We can rewrite the code as follows:</p>
<pre><code class="prettyprint">$.deferred.when($.post('/song', { id: 1 }), $.post('/song', { id: 2 }, $.post('/song', { id: 3 }).then(drawToDOM);
function drawToDOM(song1, song2, song3) {
/* draw :) */
}
</code></pre>
<p>As you can see the <code class="prettyprint">when</code> function is itself a promise which resolves once all the promises inside it has been resolved, using it we solved our previous problem in a short, maintainable and elegant way!</p>
<h1 id="conclusion_1">Conclusion <a class="head_anchor" href="#conclusion_1">#</a>
</h1>
<p>As you can see promises are an elegant way to solve the callback hell asynchronous code generates, and it’s really easy to use them! You should use them whenever you have the chance to avoid the issues exposed in this article.</p>
<p>For more information on deferreds I highly recommend watching <a href="http://www.youtube.com/watch?v=juRtEEsHI9E">this short video of jQuery conf 2012</a> which very nicely explains a lot about them. Also don’t forget to check out <a href="http://api.jquery.com/category/deferred-object/">jQuery official documentation</a>. Cheers!</p>
tag:gosukiwi.svbtle.com,2014:Post/vim-registers2014-04-22T03:52:53-07:002014-04-22T03:52:53-07:00Vim Registers<p>Vim isn’t like your standard text editor, and as such it has it’s own <br>
jargon or vocabulary; Registers are closely related to copy, cut and paste<br>
operations, as they are normally known, but in Vim it’s called yank, delete and <br>
put, at first it might just seem silly but it does have a reason as it’s much<br>
more versatile than a regular editor’s copy, cut and paste! If you are new to<br>
Vim and don’t know about registers, this is a good day! Just get some coffee,<br>
relax and read along as I guide you though the way of Vim.</p>
<p>I’ll start by explaining a bit about yank, delete and put. <strong>Yank</strong> is equivalent<br>
to copy, you yank the contents of a selection and store it, the difference<br>
is that in regular editors you only have one place to store it, if you copy<br>
another text, the old one dissapears, in Vim you have several registers, which<br>
give you so much more control! <strong>Delete</strong> is actually more related to the standard “cut”, as the text is removed but also it’s stored in a register. Finally <strong>put</strong> is equivalent to “paste” but you can choose which register to paste from.</p>
<p>Vim’s registers can be seen as a dictionary which associates a name to a <br>
stored text, Vim stores a lot of your actions in registers, such as the last change you’ve made, the current file name, the last search, and such. You can see all registers by running the <code class="prettyprint">:registers</code> command.</p>
<p>Every time you perform a yank, delete and put operation you are working with<br>
a register, by default it’s the unnamed register, you can choose which <br>
register to use by writing <code class="prettyprint">"<register-name></code> before the command, for example <br>
<code class="prettyprint">"ayw</code> will yank the current word under the cursor onto register <strong>a</strong>. <br>
As you might have deduced you can create up to 26 registers, one for each <br>
letter in the english alphabet, be careful of using other names, as some are <br>
used by Vim and some are even readonly.</p>
<p>You can also explicitly use the unnamed register by writing <code class="prettyprint">""</code> before the <br>
command, for example doing <code class="prettyprint">""yw</code> is exactly the same as doing <code class="prettyprint">yw</code>. It’s not<br>
like it’s practical but it’s good to know!</p>
<h2 id="usage-example_2">Usage example <a class="head_anchor" href="#usage-example_2">#</a>
</h2>
<p>I’ll use a simple example to demonstrate the usage of registers, which is an<br>
use case you most likely have had already. Consider the following code</p>
<pre><code class="prettyprint lang-js">var name = 'Mike';
someFunction(something);
</code></pre>
<p>Understanding the code is not important in this case, all we want to do is <br>
replace <code class="prettyprint">something</code> with <code class="prettyprint">name</code>. </p>
<pre><code class="prettyprint lang-js">var name = 'Mike';
someFunction(name);
</code></pre>
<p>At first one would try to do something like<br>
this (<code class="prettyprint">v</code> represents the cursor position):</p>
<pre><code class="prettyprint"> v
text: var name = 'Mike';
command: yiw
explanation: yank inside word
v
text: someFunction(something);
command: jf(
explanation: move down one line and position the cursor at the open parentheses
v
text: someFunction();
command: di(
explanation: delete the text inside parentheses
v
text: someFunction(something);
command: P
explanation: put the word before the cursor position
</code></pre>
<p>Oops! What happened there!? We yanked <code class="prettyprint">name</code>, but when we wanted to put it we<br>
got <code class="prettyprint">something</code>! This is because all operations share the same register by<br>
default (the unnamed register <code class="prettyprint">"</code>) so when we used <code class="prettyprint">di(</code> the delete operation<br>
used the unnamed register to store <code class="prettyprint">something</code>, replacing <code class="prettyprint">name</code> along the<br>
way.</p>
<p>There are several ways to solve this, but now that we know how to use named<br>
registers, let’s use that one!</p>
<pre><code class="prettyprint"> v
text: var name = 'Mike';
command: yiw
explanation: yank inside word
v
text: someFunction(something);
command: jf(
explanation: move down one line and position the cursor at the open parentheses
v
text: someFunction();
command: "adi(
explanation: delete the text inside parentheses and store it in the a register
v
text: someFunction(name);
command: P
explanation: put the word before the cursor position
</code></pre>
<p>Ta da! Now it works! The magic happens in <strong>step 3</strong> where we use the register <br>
a to store the deleted text, instead of the unnamed register, so we don’t lose<br>
our yanked text. Another alternative would have been using the a register<br>
for the yank command instead of the delete command.</p>
<p>An alternative solution also using named registers could be as follows:</p>
<pre><code class="prettyprint"> v
text: var name = 'Mike';
command: "ayiw
explanation: yank inside word and store it in the a register
v
text: someFunction(something);
command: jf(
explanation: move down one line and position the cursor at the open parentheses
v
text: someFunction();
command: di(
explanation: delete the text inside parentheses
v
text: someFunction(name);
command: "aP
explanation: put the text in the register a before the cursor position
</code></pre>
<p>This also works, but we require to specify the register twice instead of just<br>
once, making it a bit longer and repetitive.</p>
<h2 id="vim39s-registers_2">Vim’s registers <a class="head_anchor" href="#vim39s-registers_2">#</a>
</h2>
<p>Vim has several registers with non-letter names, such as <code class="prettyprint">0</code>, <code class="prettyprint">:</code>, <code class="prettyprint">.</code>, <code class="prettyprint">#</code>, <br>
etc. These registers are shortcuts which Vim manages on it’s own! For example,<br>
the register <code class="prettyprint">0</code> is used to store the text of yank commands, whenever you yank<br>
it stores the text in the unnamed register, and <strong>also</strong> in the register <code class="prettyprint">0</code>,<br>
which is normally called <u>the yank register</u>.</p>
<p>Knowing this, we can now solve our problem as follows</p>
<pre><code class="prettyprint"> v
text: var name = 'Mike';
command: yiw
explanation: yank inside word
v
text: someFunction(something);
command: jf(
explanation: move down one line and position the cursor at the open parentheses
v
text: someFunction();
command: di(
explanation: delete the text inside parentheses
v
text: someFunction(name);
command: "0P
explanation: put the text in the yank register before the cursor position
</code></pre>
<p>Knowledge is power, don’t you think?</p>
<h2 id="the-black-hole-register_2">The black hole register <a class="head_anchor" href="#the-black-hole-register_2">#</a>
</h2>
<p>This register is a black hole, it completely removes anything you send it. <br>
It’s named <code class="prettyprint">_</code> and we could actually use this to solve our problem from before!</p>
<pre><code class="prettyprint"> v
text: var name = 'Mike';
command: yiw
explanation: yank inside word
v
text: someFunction(something);
command: jf(
explanation: move down one line and position the cursor at the open parentheses
v
text: someFunction();
command: "_di(
explanation: delete the text inside parentheses and send the contents to a mystical black hole
v
text: someFunction(name);
command: P
explanation: put the word before the cursor position
</code></pre>
<p>This is pretty similar as we did with the <code class="prettyprint">a</code> register but this time we<br>
make sure there’s nothing there we can replace, as we’ll never be able to<br>
put the contents of the black hole register!</p>
<h2 id="using-registers-in-insert-mode_2">Using registers in Insert Mode <a class="head_anchor" href="#using-registers-in-insert-mode_2">#</a>
</h2>
<p>Another way to use registers is from Insert Mode, here we just do <code class="prettyprint"><Ctrl> + <R></code><br>
or <code class="prettyprint"><C-R></code> for short, and the name of the register to add it’s contents after <br>
the cursor position.</p>
<p>Going back to our awesome overused example</p>
<pre><code class="prettyprint"> v
text: var name = 'Mike';
command: yiw
explanation: yank inside word
v
text: someFunction(something);
command: jf(
explanation: move down one line and position the cursor at the open parentheses
v
text: someFunction(name);
command: ci(<c-r>0<esc>
explanation: change the contents of the text inside parentheses, put the contents of the yank register (register 0) and go back to normal mode
</code></pre>
<p>As you can see the last step is pretty big, as we are actually doing two things<br>
at once, changing the text and putting the text from the yank register.</p>
<h2 id="yet-another-example_2">Yet another example <a class="head_anchor" href="#yet-another-example_2">#</a>
</h2>
<p>Using visual mode we can do something pretty similar as we did above, but<br>
it might be more intuitive.</p>
<pre><code class="prettyprint"> v
text: var name = 'Mike';
command: yiw
explanation: yank inside word
v
text: someFunction(something);
command: jf(
explanation: move down one line and position the cursor at the open parentheses
v
text: someFunction(name);
command: vi(p
explanation: Using visual mode select the text inside the parentheses, then replace it with the content of the unnamed register
</code></pre>
<p>Because we are actually doing two steps at once we don’t have the problem of<br>
the register beeing replaced up until we already replaced the word we wanted.<br>
Once the word has been replaced the unnamed register will be <code class="prettyprint">something</code>.</p>
<h1 id="the-system-clipboard-register_1">The system clipboard register <a class="head_anchor" href="#the-system-clipboard-register_1">#</a>
</h1>
<p>Registers are nice and dandy but regular system programs do not have registers,<br>
and sometimes you want to share data back and forth, for example, copying some<br>
text from a website. This is what the <code class="prettyprint">+</code> register does, it’s the system <br>
register, you can write and read from it, to paste the contents of something<br>
you copied onto vim you just do <code class="prettyprint">"+p</code> from Normal Mode or <code class="prettyprint"><C-R>+</code> from <br>
Insert Mode.</p>
<p>Writing text onto the system’s clipboard is also easy! Just using <code class="prettyprint">"+y</code> will do.</p>
<h2 id="using-ctrl-v-and-ctrl-c-in-vim_2">Using Ctrl + V and Ctrl + C in Vim <a class="head_anchor" href="#using-ctrl-v-and-ctrl-c-in-vim_2">#</a>
</h2>
<p>This is something pretty much all editors on Windows share and it’s sometimes<br>
quite shocking not having these hotkeys, you can easily use them in Vim by<br>
adding the following to your <code class="prettyprint">vimrc</code> file</p>
<pre><code class="prettyprint">" Windows-like clipboard
vm <c-x> "+x
vm <c-c> "+y
cno <c-v> <c-r>+
exe 'ino <script> <C-V>' paste#paste_cmd['i']
</code></pre>
<h1 id="the-expression-register_1">The expression register <a class="head_anchor" href="#the-expression-register_1">#</a>
</h1>
<p>The expression register is named <code class="prettyprint">=</code> and it’s an exception, meaning this<br>
register does not store text, but you can use it to evaluate a vimscript<br>
expression and use the returned value.</p>
<p>For example, from insert mode you can do <code class="prettyprint"><c-r>=</code> now the command line mode<br>
enables, simply by entering <code class="prettyprint">2+2</code> and pressing <code class="prettyprint"><enter></code> you will now<br>
insert the result of that expression, in this case 4.</p>
<h1 id="some-other-registers_1">Some other registers <a class="head_anchor" href="#some-other-registers_1">#</a>
</h1>
<p>Vim handles several registers, such as</p>
<pre><code class="prettyprint">% - Name of the current file
# - Name of the alternate file
. - Last inserted text
: - Last ex command
/ - Last search pattern
</code></pre>
<p>For a complete list of Vim’s registers just do <code class="prettyprint">:help registers</code>.</p>
<h1 id="conclusion_1">Conclusion <a class="head_anchor" href="#conclusion_1">#</a>
</h1>
<p>Registers are one of the many features which make Vim different from the rest,<br>
and once you get used to it, it’s quite convenient! It enables you to do some <br>
nifty things in no time with very little effort. A related topic if you want<br>
to dive deeper is Macros, which I might explain in another post, as it would be <br>
an overkill in this one! Personally I like to absorb one topic per day, and <br>
steadily work on it.</p>
<p>I Hope you find this little article useful! Cheers!</p>