Deon Heyns2018-07-29T13:12:02+00:00http://deonheyns.comDeon HeynsStart and Stop SQL Server Using a Script2017-11-04T00:00:00+00:00http://deonheyns.com/posts/start-and-stop-sql-server-using-a-script<p>This is a simple CMD script that will start or stop SQL Server. SQL Server can be a memory and processor hog so I usually
set my SQL Server startup to Manual and use the script to toggle its running state. You will need to run the script as
administrator.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>echo off
for /F "tokens=3 delims=: " %%H in ('sc query "MSSQLSERVER" ^| findstr " STATE"') do (
if /I "%%H" NEQ "RUNNING" (
net start MSSQLSERVER
)
if /I "%%H" NEQ "STOPPED" (
net stop MSSQLSERVER
)
)
PAUSE
</code></pre></div></div>
<p>Hopefully this will be helpful to others…</p>
<hr />
Installing RabbitMQ on Windows...2017-10-04T00:00:00+00:00http://deonheyns.com/posts/installing-rabbitmq-on-windows<p>These are my notes on getting RabbitMQ up and running on Windows. Everytime I do this install there are new
gotchas. I’ll update this with any new findings</p>
<ol>
<li>Download Erlang and install</li>
<li>Download RabbitMQ and install</li>
<li>Check if this file C:\Windows.erlang.cookie and this file C:\Users\youruser.erlang.cookie are equals. If not, copy C:\Windows.erlang.cookie to C:\Users\youruser.erlang.cookie</li>
<li>Run: RabbitMQ sbin command prompt as administrator.</li>
<li>Run: “rabbitmq-service remove”</li>
<li>Run: “rabbitmq-service install”</li>
<li>Run: net start rabbitmq</li>
<li>Run: rabbitmq-plugins enable rabbitmq_management</li>
<li>Run: rabbitmq-plugins enable rabbitmq_shovel</li>
<li>open the management portal http://localhost:15672</li>
</ol>
<p>Queues are great!</p>
<hr />
Could Not Load File or Assembly 'Microsoft.SqlServer.BatchParser Version=12.0.0.0 Culture=neutral2017-08-24T00:00:00+00:00http://deonheyns.com/posts/could-not-load-file-or-assembly-microsoft.sqlserver.batchparser-version=12.0.0.0-culture=neutral<p>If you see this error:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>could not load file or assembly 'microsoft.sqlserver.batchparser version=12.0.0.0 culture=neutral
</code></pre></div></div>
<p>Then head over to <a href="https://www.microsoft.com/en-us/download/details.aspx?id=42295">Microsoft Download center</a>
and install</p>
<ul>
<li>ENU\x64\SharedManagementObjects.msi for X64 OS</li>
<li>ENU\x86\SharedManagementObjects.msi for X86 OS</li>
<li>ENU\x64\SQLSysClrTypes.msi</li>
<li>ENU\x86\SQLSysClrTypes.msi</li>
</ul>
<p>That should do the trick</p>
<hr />
Create A Geocoding Service On The Cheap2015-04-25T00:00:00+00:00http://deonheyns.com/posts/create-a-geocoding-service-on-the-cheap<blockquote>
<p>Gecoding, because everyone needs to know the lat long for their address - Jay-Z</p>
</blockquote>
<p>I have been doing some work with spatial data lately and one of the things I have needed to do
is geocode addresses. If you need to do some simple geocoding then the services available from
Google, Bing, Baidu, Yahoo etc. are great. However, if need to start geocoding at scale then you
run into rate limiting issues.</p>
<p>Unfortunately these services are on the pricey side and an open source solution is always better
than a paid one. Postgresql and PostGIS is know for their awesome spatial abilities which make it
super simple to do spatial queries. One thing you still need are shapefiles with the necessary data.
The census.gov site has all the necessary shapefiles needed to make this happen.</p>
<p>The PostGIS site has a tutorial on how to get the postgis_tiger_geocoder installed but I struggled for more
than a day following their instructions. So after hours and hours of struggling I finally got everything working
and now it’s time for me to share the steps that you don’t have to struggle like I did.</p>
<p>Lets get started.</p>
<p>These steps assume you are using Ubuntu.</p>
<h3 id="step-0">Step 0.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo apt-get update
sudo apt-get upgrade
sudo apt-get install postgresql
sudo apt-get install postgis-2.1 wget unzip
</code></pre></div></div>
<h3 id="step-1">Step 1.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo adduser postgres sudo
sudo passwd postgres
touch /var/lib/postgresql/.psql_history
</code></pre></div></div>
<h3 id="step-2">Step 2.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>su postgres
psql
\password postgres
CREATE DATABASE geocoder;
</code></pre></div></div>
<h3 id="step-3">Step 3.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>CREATE EXTENSION postgis;
CREATE EXTENSION postgis_topology;
CREATE EXTENSION fuzzystrmatch;
CREATE EXTENSION postgis_tiger_geocoder;
</code></pre></div></div>
<h3 id="step-4">Step 4.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>GRANT USAGE ON SCHEMA tiger TO PUBLIC;
GRANT USAGE ON SCHEMA tiger_data TO PUBLIC;
GRANT SELECT, REFERENCES, TRIGGER ON ALL TABLES IN SCHEMA tiger TO PUBLIC;
GRANT SELECT, REFERENCES, TRIGGER ON ALL TABLES IN SCHEMA tiger_data TO PUBLIC;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA tiger TO PUBLIC;
ALTER DEFAULT PRIVILEGES IN SCHEMA tiger_data GRANT SELECT, REFERENCES ON TABLES TO PUBLIC;
</code></pre></div></div>
<h3 id="step-5">Step 5.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo mkdir /gisdata
sudo mkdir /gisdata/temp
cd /gisdata
sudo chmod 777 .
cd temp
sudo chmod 777 .
</code></pre></div></div>
<h3 id="step-6">Step 6.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>psql
\c geocoder
Generate nationscript
\t
\a
\o /gisdata/nationscript.sh
SELECT loader_generate_nation_script('sh');
\o
</code></pre></div></div>
<h3 id="step-7">Step 7.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Generate statescript
\t
\a
\o /gisdata/statescript.sh
SELECT loader_generate_script(ARRAY['CT'],'sh');
\o
</code></pre></div></div>
<h3 id="step-8">Step 8.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo nano nationscript.sh
TMPDIR="/gisdata/temp/"
UNZIPTOOL=unzip
WGETTOOL="/usr/bin/wget"
export PGBIN=/usr/bin
export PGPORT=5432
export PGHOST=localhost
export PGUSER=postgres
export PGPASSWORD=postgres
export PGDATABASE=geocoder
PSQL=${PGBIN}/psql
SHP2PGSQL=${PGBIN}/shp2pgsql
cd /gisdata
</code></pre></div></div>
<h3 id="step-9">Step 9.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo nano statescript.sh
TMPDIR="/gisdata/temp/"
UNZIPTOOL=unzip
WGETTOOL="/usr/bin/wget"
export PGBIN=/usr/bin
export PGPORT=5432
export PGHOST=localhost
export PGUSER=postgres
export PGPASSWORD=postgres
export PGDATABASE=geocoder
PSQL=${PGBIN}/psql
SHP2PGSQL=${PGBIN}/shp2pgsql
cd /gisdata
</code></pre></div></div>
<h3 id="step-10">Step 10.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>chmod a+x nationscript.sh
chmod a+x statescript.sh
sudo ./nationscript.sh
sudo ./statescript.sh
</code></pre></div></div>
<h3 id="step-11">Step 11.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>psql
\c geocoder
SELECT install_missing_indexes();
</code></pre></div></div>
<h3 id="step-12">Step 12.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>edit:
/etc/postgresql/&lt;version&gt;/main/postgresql.conf
listen_addresses='localhost' =&gt; listen_addresses='*'
</code></pre></div></div>
<h3 id="step-13">Step 13.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>edit:
/etc/postgresql/&lt;version&gt;/main/pg_hba.conf
IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
to:
IPv4 local connections:
host all all 127.0.0.1/32 md5
host all all 0.0.0.0/0 md5
# IPv6 local connections:
</code></pre></div></div>
<h3 id="step-14">Step 14.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>sudo service postgresql restart
</code></pre></div></div>
<h3 id="step-15">Step 15.</h3>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>psql
\c geocoder
SELECT
g.rating As rating,
ST_X(g.geomout)::numeric(10,5) As lon,
ST_Y(g.geomout)::numeric(10,5) As lat,
(g.addy).address As snum,
(g.addy).streetname || ' '
|| (g.addy).streettypeabbrev As street,
(g.addy).zip,
geomout as geom
FROM geocode('1241 East Main Street Stamford, CT 06902',1) As g;
</code></pre></div></div>
<p>If everything worked correctly and I really hope it did (I was able to consistently get up and running following these steps)
you will have an address returned which includes the latitude and longitude.</p>
<hr />
Heroku Style Deployments With git-deploy2015-01-24T00:00:00+00:00http://deonheyns.com/posts/heroku-style-deployments-with-git-deploy<blockquote>
<p>Ever since I started using git-deploy I spend more time on chilling - William Henry Harrison</p>
</blockquote>
<p>I have been working more and more on *nix systems lately and a lot less with Windows. Thus, I have deployed a fair amount of apps to Heroku as of late. One thing I enjoy about deploying to Heroku is how using git you can push your code to the server. To give you an example, after installing the Heroku Toolbelt, quite simply all you need to do to deploy is from within your repo:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ heroku create
$ git push heroku master
</code></pre></div></div>
<p>Heroku will go ahead and build your application while you sit back and relax. I think this is awesome, but, was wondering how I can do this on a local server? Now before I introduce you to <a href="https://github.com/mislav/git-deploy">git-deploy</a> let me tell you that you can do the same using git hooks but I think <a href="https://github.com/mislav/git-deploy">git-deploy</a> is a nice abstraction.</p>
<h2 id="lets-go">Lets GO!</h2>
<p>I am going to be using Ubuntu 12.04.4 LTS server that I have running on VirtualBox. This is a clean install and I am going to only show how we get this server ready to be deployed to.</p>
<p>Firstly you will need to install git on the remote server, since <a href="https://github.com/mislav/git-deploy">git-deploy</a> uses <a href="http://ruby-lang.org">Ruby</a> to execute deploy ments scripts you will need to install <a href="http://ruby-lang.org">Ruby</a> too. I am on an Ubuntu box so I will use the following command:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root@super-server:/home# apt-get install git
</code></pre></div></div>
<p>It is good practice to have your application run by a service account; we will, therefore, create a new user on our server to run our example application. <del>Now one thing that isn’t so great is the fact that we need to add our new user to the sudo group but this is key for this to work.</del> Log into the server as root or sudo the below commands:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root@super-server:/home# adduser donkey
</code></pre></div></div>
<p>For this to work OpenSSH or equivalent should be installed on your server. The remote server is going to need a copy of the ssh keys for each user who will be push changes to it via git. Copy your ssh key into the authorized_keys file in the .ssh directory of the service user.</p>
<p>On your local machine copy your ssh key using:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ pbcopy &lt; ~/.ssh/id_rsa.pub
</code></pre></div></div>
<p>Back on the remote server use vi to edit the authorized_keys file:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root@super-server:/home# cd donkey
root@super-server:/home/donkey# mkdir .ssh &amp;&amp; chmod 700 .ssh
root@super-server:/home/donkey# touch .ssh/authorized_keys &amp;&amp; chmod 600 .ssh/authorized_keys
root@super-server:/home/donkey# vi .ssh/authorized_keys
</code></pre></div></div>
<p>This will open up vi paste your ssh key and make sure to save your changes. To make sure everything is in order we restart the ssh server:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>root@super-server:/home/donkey/.ssh# stop ssh ; start ssh
</code></pre></div></div>
<p>Now jump back to your local machine. For this to all work you are going to need Ruby and RubyGems installed on your local machine. Keep in mind this is only applicable to the user who is going to set up the git deploy, everyone else is just going to add a remote to the server where the deployed application will reside.</p>
<p>With Ruby and RubyGems installed you can install git-deploy:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ gem install git-deploy
</code></pre></div></div>
<p>Now navigate to your repository and we will setup using git-deploy. For my application, I have the following structure:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kong/
└── app
└── index.html
</code></pre></div></div>
<p>##Show me the money</p>
<p>My application is already under source control, so I don’t need to run git init on it; rather I can just add a remote that points to the production server.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git remote add production 'donkey@192.168.1.119:/home/donkey/kong'
</code></pre></div></div>
<p>I can now run the following commands that will setup the necessary hooks on the remote server</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git deploy setup -r production
[production] $ mkdir -p /home/donkey/kong
[production] $ cd /home/donkey/kong &amp;&amp; \
git init &amp;&amp; \
git config receive.denyCurrentBranch ignore
Initialized empty Git repository in /home/donkey/kong/.git/
FILE: [local] hooks/post-receive.sh -&gt; [production] /home/donkey/kong/.git/hooks/post-receive
[production] $ chmod +x /home/donkey/kong/.git/hooks/post-receive
</code></pre></div></div>
<p>At this stage, we need to create the folder that will contain the script files that will run after we have pushed our changes. So still on our local machine run the following:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git deploy init
create deploy/after_push
chmod deploy/after_push
create deploy/restart
chmod deploy/restart
create deploy/before_restart
chmod deploy/before_restart
</code></pre></div></div>
<p>It’s pretty clear what the purpose of these scripts are but here is a short description.</p>
<p>###after_push</p>
<p>This file is will be run after you’ve pushed your code to the remote server. It gathers some information about your changes, sets up the environment and kicks off the before_restart and restart scripts.</p>
<p>###before_restart</p>
<p>Use this script to run migrations or make any changes necessary before the application starts up.</p>
<p>###restart</p>
<p>This is where you will add the commands to start your application.</p>
<p>##Here We Go</p>
<p>You will edit or add additional scripts that will be called from these scripts to ensure all setup is correct for your application. At this point our folder structure will look as follows:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kong/
├── app
│ └── index.html
└── deploy
├── after_push
├── before_restart
└── restart
</code></pre></div></div>
<p>The next step is to commit our changes to source control:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git add --all
$ git commit -m "Repo setup to be used with git-deploy"
</code></pre></div></div>
<p>Now comes the awesomeness, it’s time to push our changes to the server.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git push -u production master
Counting objects: 8, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (8/8), 1.33 KiB | 0 bytes/s, done.
Total 8 (delta 0), reused 0 (delta 0)
remote: HEAD is now at 03970d6 Repo setup to be used with git-deploy
To donkey@192.168.1.119:/home/donkey/kong
* [new branch] master -&gt; master
Branch master set up to track remote branch master from production.
</code></pre></div></div>
<p>I have a web server running on the remote server that will display the index.html page:</p>
<p><img src="http://deonheyns.com/images/git-deploy-hello-world.jpg" alt="hello world" /></p>
<p>To prove that everything is in working order I will change the text of that page from:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="o">&lt;</span><span class="n">h1</span><span class="o">&gt;</span><span class="no">Hello</span><span class="p">,</span> <span class="no">World</span><span class="o">&lt;</span><span class="sr">/h1&gt;</span></code></pre></figure>
<p>To this:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="o">&lt;</span><span class="n">h1</span><span class="o">&gt;</span><span class="no">Hello</span><span class="p">,</span> <span class="n">git</span><span class="o">-</span><span class="n">deploy</span><span class="o">&lt;</span><span class="sr">/h1&gt;</span></code></pre></figure>
<p>Then I make sure to commit my code to source control and push to the server:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git add --all
$ git commit -m "Updated h1 text"
[master 224ca0a] Updated h1 text
1 file changed, 1 insertion(+), 1 deletion(-)
$ git push -u production master
</code></pre></div></div>
<p>And viola:
<img src="http://deonheyns.com/images/git-deploy-hello-git-deploy.jpg" alt="hello git-deploy" /></p>
<hr />
2014 - My Year In Review2014-12-31T00:00:00+00:00http://deonheyns.com/posts/my-year-in-review-2014<p>I have seen a few people pen these posts, so here are my achievements and failures of the last 12 months and a few corrective measures I will take. Note these are just bullet points and I post them here to keep myself honest:</p>
<h2 id="what-went-well">What Went Well?</h2>
<ul>
<li>I Lost 40 pounds</li>
<li>Became more healthy</li>
<li>Learned Ruby</li>
<li>Learned Python</li>
<li>Learned Scala</li>
<li>Started blogging and went 3 months non-stop blogging</li>
<li>Got JIRA used throughout my whole company. Development, Portfolio Analytics, Modeling and Support</li>
<li>Delivered a bunch of improvements to our investor web portal</li>
<li>Developed an application to manage our investors’ security</li>
<li>Established a good product team</li>
<li>Built good relationships within the organization</li>
<li>Traveled to Costa Rica, Nashville, San Francisco, San Diego, Miami, Fort Lauderdale, Columbia SC, Charlotte, Birmingham Alabama, Birmingham UK, Bath, Bristol, Exeter, Truro.</li>
<li>Ran a 5k race</li>
<li>Ran a 10k race</li>
<li>Built <a href="http://www.initials-avatar.com/" target="__blank">Initials Avatar</a></li>
<li>Built <a href="http://www.titleize.com/" target="__blank">Titleize</a></li>
</ul>
<h2 id="what-went-badly">What Went Badly?</h2>
<ul>
<li>Hurt my knee over-running</li>
<li>Didn’t run the Marathon I wanted</li>
<li>Didn’t invest enough</li>
<li>Didn’t save enough</li>
<li>Didn’t write a complete app in Scala</li>
<li>Didn’t continue blogging</li>
<li>Spent too much money on online purchases</li>
<li>Spent too much time on TV</li>
</ul>
<h2 id="what-can-i-change">What Can I Change?</h2>
<ul>
<li>Come up with a realistic savings plan</li>
<li>Choose a running plan and stick to it</li>
<li>Add books to a wish list that each month I can groom and serves as my reading list. Purchase a new book only after reading all existing</li>
<li>Create a plan to blog at least once a week</li>
<li>Spend less time on TV</li>
</ul>
<hr />
Dude! What happened to you?2014-12-31T00:00:00+00:00http://deonheyns.com/posts/dude-what-happened-to-you<h2 id="where-have-you-been">Where have you been?</h2>
<blockquote>
<p>I been gone for a minute now; I’m back at the jump off - Lil’ Kim</p>
</blockquote>
<p>I made a small detour, well quite a big one. Since the second half of September I have been part of a project that has sucked up all my time. It’s one of those projects that is super stressful, but at the same time super exciting. Therefore, I have had no time to blog or had any time to dedicate to Ruby or my quest to submit a pull request to Rails.</p>
<h2 id="so-you-failed">So you failed?</h2>
<p>Do I view this as failing? I could, but I don’t, if anything I believe the months of continuous blogging and learning aided me in getting pulled into this exciting project. I might have missed my deadline but all this means is that my timeline has been shifted on. In the coming year when things settle down I will get back to my original goals as I have outlined on this blog.</p>
<h2 id="so-what-is-next">So what is next?</h2>
<p>I suspect 15Q1, and most of 15Q2 is going to be just as hectic. Honestly I only found time for this post as I am in the UK with a cold and ear infection and took a sick day, all the while supposedly being on holiday. I have been writing tons of Python and been working with Pandas DataFrames the last few months in addition to my other duties as part of this project. I would like to go back to these Python scripts and rewrite them to Ruby and share them with you all.</p>
<h2 id="what-do-you-mean-python-thought-you-were-a-c-guy">What do you mean Python? Thought you were a C# guy?</h2>
<p>I am, well my company predominately uses C#. However for certain things C# is fantastic and for others it’s not so great. If you are going to be building a line of business system, then C# is good at that and so is Ruby and Python. If you need to do some quick data manipulation, data munging or web scraping then Python and Ruby are fantastic. I have been using Python due to some of the great statistical and math libraries available.</p>
<h2 id="so-what-are-the-new-timelines">So what are the new timelines?</h2>
<p>I need to work on those; I am going to take a few days to recover from my sickness and will write something up and share that here. However, like I said above the first half of next year is going to be just as busy if not busier than the last three months.</p>
<h2 id="we-miss-you">We miss you!</h2>
<p>I miss you too ;)</p>
<hr />
Ruby - What are Symbols? When and How Do I Use Them2014-09-23T00:00:00+00:00http://deonheyns.com/posts/ruby-what-are-symbols-when-and-how-do-i-use-them<p>Ruby has a built-in class called Symbol, Symbols are very interesting in that I have not seen anything similar in C#, Java or JavaScript. I think of Symbols being similar to Enums and somewhat string-ish. Symbols are immutable meaning their value can not be changed once set.</p>
<p>Running any of this code will result in a NoMethodError:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>:abc + :a
:abc + a
:abc + 'a'
:abc &lt;&lt; :a
</code></pre></div></div>
<p>So as you can see there is no appending or adding of any strings or Symbols to another Symbol. This immutability is great as it gives us a great why to represent something that is unique. Symbols can’t change thus they are unique. The Symbol ‘:abcd’ no matter where it is called in you code is the same ‘:abcd’ object. You can test this out in IRB, first let’s look how two strings with the same value have different ‘object_ids’:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>'abcd'.object_id
=&gt; 70277954526800
'abcd'.object_id
=&gt; 70277954509020
</code></pre></div></div>
<p>Now compare that with two Symbols that have the same value:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>:abcd.object_id
=&gt; 541448
:abcd.object_id
=&gt; 541448
</code></pre></div></div>
<p>Le bam! Same Symbol same ‘object_id’. This makes Symbols perfect to use as keys in a Hash / Dictionary. Symbols are very unknown coming from the .NET world but are pretty straight-forward and are an excellent tool in the belt.</p>
<hr />
Ruby - Generate an Excel Spreadsheet2014-09-22T00:00:00+00:00http://deonheyns.com/posts/ruby-generate-an-excel-spreadsheet<p>In the financial world, there are always Excel spreadsheets; spreadsheets and Excel dominate most Fortune 500 Companies.
Many times a business person will ask that a bunch of data is put in an Excel spreadsheet for them to manipulate. There are many ways to do this in the C# and .NET world, but how do we skin this cat in Ruby?</p>
<p>In Ruby we can use the Axlsx library, this is a cool library. With Axlsx you can create excel worksheets with charts, images (with links), automated and fixed column widths, customized styles, functions, tables, conditional formatting, print options, comments, merged cells, auto filters, file and stream serialization as well as full schema validation.</p>
<p>Enough talk, let’s dive into the code:</p>
<script src="https://gist.github.com/DeonHeyns/3884d60702d2d288eb2a.js"> </script>
<p>Axlsx has a concept of Package, which holds the Workbook that in turns hold the different Worksheets. In the code above we create a package and from the package variable we retrieve the Workbook. To add a Worksheet you call the ‘add_worksheet’ method on the workbook, passing in a has to for the name. The ‘add_worksheet’ method takes a code block and from the code example you see you can call ‘add_row’ to start adding items into the rows of the worksheet. To save the spreadsheet to disk you call the ‘serialize’ method on the ‘package’ variable passing in the filename. Opening this Excel spreadsheet, you will see a column for income and a column for expense with values below these columns. How easy was that?</p>
<p>There are a bunch of examples available on the GitHub repository for Axlsx; I can see myself using this library quite often going forward.</p>
<hr />
Ruby - Converting Image Formats2014-09-21T00:00:00+00:00http://deonheyns.com/posts/ruby-converting-image-formats<p>So my streak has been broken, in total I have missed three days of posting. Last week Saturday I was man down after flying from San Francisco to Bermuda and this weekend has been crazy with work and a lack of sleep. It is clear I need to take my own advice and get some <a href="http://deonheyns.com/posts/on-the-importance-of-rest/">rest</a>.</p>
<p>However, tonight I want to share a cool way to convert from one image format to another. RMagick is a binding from Ruby to the ImageMagick and GraphicsMagick image manipulation libraries. ImageMagick is a software suite to create, edit, compose, or convert bitmap images. It can read and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PNG, Postscript, SVG, and TIFF. Use ImageMagick to resize, flip, mirror, rotate, distort, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves.</p>
<p>Now let’s go ahead and convert a PNG to JPG. This is our image:</p>
<p><img src="http://deonheyns.com/images/cat.png" alt="cat png" /></p>
<p>First make sure you have installed ImageMagick from their website. Next go ahead and install the RMagick gem which is a Ruby binding to ImageMagick.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem install rmagick
</code></pre></div></div>
<p>Next we can create a script file to hold our code, the first line will be a require statement to ‘rmagick’. Let’s have a look at the complete code and talk through it.</p>
<script src="https://gist.github.com/DeonHeyns/a6e7b27f163de96cb181.js"> </script>
<p>The code is straightforward; the only thing that tripped me up was when calling RMagick’s read method it returns an array so make sure you call first or use the appropriate index for the image you want.</p>
<p>The code above shows how we read in the image from the disk. To convert this image, you call the write method passing in the new filename including the extension.</p>
<p>After the code has run we are let with a new cat file which is a jpg:</p>
<p><img src="http://deonheyns.com/images/cat.jpg" alt="cat png" /></p>
<p>To show you that this works correctly, I went ahead and read the newly created image and print out its format. This is a nice little utility that I have been using to convert quickly between different formats. The cool thing is that Magick supports a bunch of different file formats, so, checkout their <a href="http://www.imagemagick.org/">site</a>.</p>
<hr />
Simple Profiling of a Ruby Application2014-09-18T00:00:00+00:00http://deonheyns.com/posts/simple-profiling-of-a-ruby-application<p>A few days back I wrote about benchmarking your Ruby code, today I want to show you quickly how to profile your code. We have all been there, slow code, select n+1 and all the other craziness that goes on when you write code. You end up putting in code to time blocks of code, or you buy a third-party profiler to tell you where you code is crap.</p>
<p>Ruby has a built-in crap-o-meter, and it is part of the Standard Library so you can use it for free!</p>
<script src="https://gist.github.com/DeonHeyns/a3a6ae7bb5244c207b21.js"> </script>
<p>As you can see in the code, one little require bringing in the ‘profile’ library, and that is it. Running this code outputs:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668068375
% cumulative self self total
time seconds seconds calls ms/call ms/call name
50.00 0.02 0.02 1874 0.01 0.01 Bignum#+
50.00 0.04 0.02 999 0.02 0.04 nil#
0.00 0.04 0.00 1 0.00 40.00 Range#each
0.00 0.04 0.00 1 0.00 0.00 TracePoint#enable
0.00 0.04 0.00 1 0.00 0.00 Module#method_added
0.00 0.04 0.00 999 0.00 0.01 Object#add
0.00 0.04 0.00 1 0.00 0.00 Bignum#to_s
0.00 0.04 0.00 2 0.00 0.00 IO#write
0.00 0.04 0.00 1 0.00 0.00 IO#puts
0.00 0.04 0.00 1 0.00 0.00 Kernel#puts
0.00 0.04 0.00 1 0.00 0.00 TracePoint#disable
0.00 0.04 0.00 1 0.00 40.00 #toplevel
</code></pre></div></div>
<p>Pretty interesting stuff right? All I needed was a require and I get some awesome profiling. You would obviously want to hide this behind a flag of some sorts. Nonetheless awesomeness!</p>
<hr />
Ruby - Aliasing Methods, Just Because You Can2014-09-17T00:00:00+00:00http://deonheyns.com/posts/ruby-aliasing-methods-just-because-you-can<p>Ruby gives you a way to alias a method, what this means is you can call the method Foo and alias it as Bar and when a user of the class calls Bar the call is proxied to Foo. My libraries and classes evolve over time, being able to alias’ methods allow you to keep method names around as you deprecate certain functionality</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="n">job</span><span class="p">)</span>
<span class="nb">puts</span> <span class="s1">'executing job'</span>
<span class="k">end</span></code></pre></figure>
<p>So should method be renamed from run to execute we have a way to ensure that any other calling code won’t break. Let’s look at a practical example.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Awesome</span>
<span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="c1"># do some work...
</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="n">awesome</span> <span class="o">=</span> <span class="no">Awesome</span><span class="p">.</span><span class="nf">new</span>
<span class="n">awesome</span><span class="p">.</span><span class="nf">run</span></code></pre></figure>
<p>Now if we changed the run method to execute without using alias and keeping all the code as it stands we would break any callers.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Awesome</span>
<span class="k">def</span> <span class="nf">execute</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="c1"># do some work...
</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="n">awesome</span> <span class="o">=</span> <span class="no">Awesome</span><span class="p">.</span><span class="nf">new</span>
<span class="n">awesome</span><span class="p">.</span><span class="nf">run</span></code></pre></figure>
<p>This code will result in an exception:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>NoMethodError: undefined method `run' for main:Object
</code></pre></div></div>
<p>To remedy this we use alias to ensure nothing breaks.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Awesome</span>
<span class="k">def</span> <span class="nf">execute</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="c1"># do some work...
</span>
<span class="k">end</span>
<span class="k">alias</span> <span class="ss">:run</span> <span class="ss">:execute</span>
<span class="k">end</span>
<span class="n">awesome</span> <span class="o">=</span> <span class="no">Awesome</span><span class="p">.</span><span class="nf">new</span>
<span class="n">awesome</span><span class="p">.</span><span class="nf">run</span></code></pre></figure>
<p>Now the code works again. One important thing to remember here is to make sure the alias call is made after the declaration of the method, failing to do so will result in a ‘NoMethodError.’</p>
<p>What a great way to ensure backward compatibility, but also a way to migrate use of a library over time without breaking dependent code.</p>
<hr />
Ruby - Ping A Machine2014-09-16T00:00:00+00:00http://deonheyns.com/posts/ruby-ping-a-machine<p>Whenever I cannot reach a website that is hosted internally at my company, I always ping it before taking any further steps. Today I pinged a machine and thought ‘I wonder how I do this in Ruby?’ Well, that’s what I am going to show you quickly.</p>
<p>First install the net-ping gem:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem install net-ping
</code></pre></div></div>
<script src="https://gist.github.com/DeonHeyns/1fc7e1a701d0d27f50fc.js"> </script>
<p>That is all I needed to do, just install the net-ping gem, create a new ‘External’ object and call ping passing in the machine name, port and timeout value.</p>
<p>Ruby is just so awesome! Short and sweet, straight to the answer!</p>
<hr />
Ruby - How To Mask a Command-line Password2014-09-15T00:00:00+00:00http://deonheyns.com/posts/ruby-how-to-mask-a-commandline-password<p>When writing command-line applications, one thing you might need is a user’s password. Obviously a password prompt should be masked or at least hidden from anyone who might walk past you. So how do we do this in Ruby without breaking a sweat?</p>
<p>Enter <a href="https://github.com/JEG2/highline">Highline</a>:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>HighLine was designed to ease the tedious tasks of doing console input and output with low-level methods like gets() and puts(). HighLine provides a robust system for requesting data from a user, without needing to code all the error checking and validation rules and without needing to convert the typed Strings into what your program really needs. Just tell HighLine what you're after, and let it do all the work.
</code></pre></div></div>
<script src="https://gist.github.com/DeonHeyns/e3ec88ace94efd5c0268.js"> </script>
<p>Running this and typing in ‘password’ will output:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Hey dude choose a password: ********
Your password is 'password'
</code></pre></div></div>
<p>So just install the ‘highline’ gem, create a method that takes a message and a mask. The mask will be printed to the screen every time you type a character. Then call this method passing in your message and bam you can hide the characters as they are type.</p>
<hr />
Simple Benchmarking in Ruby2014-09-14T00:00:00+00:00http://deonheyns.com/posts/simple-benchmarking-in-ruby<p>I want to go into a bit of benchmarking. Often on Twitter you will see developers tweet about some statistics around benchmarking that they are doing. So what is the definition of benchmarking? Benchmarking is to evaluate or check (something) by comparison with a standard.</p>
<p>You might want to measure and log execution times to work out what the benchmark of you program is or you could possibly measure the time taken to call a web service, collect this data and then have a way to benchmark performance.</p>
<p>So how can you do this in Ruby? That is the exact question I asked myself; I wanted something simple to measure the User CPU Time, System CPU Time, User + System CPU Time and finally Real Elapsed Time.</p>
<p>Ruby, as usual has us covered. Included in the Standard Library is Benchmark. Therefore, all you need to do is add a require to the benchmark class to pull in all the bits you need.</p>
<p>Here are our requirements, measure the differences between using a for loop, the ‘times’ method and the ‘upto’ method based on 1000000 iterations.</p>
<p>Now drum roll please as this is some hectic code!</p>
<script src="https://gist.github.com/DeonHeyns/12eeb19b78d61f06e93b.js"> </script>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code> user system total real
for loop 0.050000 0.000000 0.050000 ( 0.056730)
times 0.060000 0.000000 0.060000 ( 0.055071)
upto 0.050000 0.000000 0.050000 ( 0.055136)
</code></pre></div></div>
<p>Easy right? The ‘bm’ method generates sequential reports with labels. Meaning it will display your reports in the order they were executed and with the text passed into the ‘report’ method.</p>
<p>Real nice how about a more real-life example? Hypothetically speaking let us say we have some code that works out whether or not a number is or is not a prime number. We want to measure the execution of this code run 100000 times.</p>
<p>First here is the code we will use to determine whether the number passed in is a prime number.</p>
<script src="https://gist.github.com/DeonHeyns/c717a90a234e04f722e5.js"> </script>
<p>Here is the code that will measure the execution time:</p>
<script src="https://gist.github.com/DeonHeyns/fb072170c828cc29a542.js"> </script>
<p>This code outputs the following on my machine:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code> user system total real
is prime number over 100000 executions 0.300000 0.000000 0.300000 ( 0.295098)
</code></pre></div></div>
<p>As usual Ruby has us covered with some of it’s awesome built-in functionality. Go forth and benchmark all the things.</p>
<p><img src="http://deonheyns.com/images/benchmark.jpg" alt="Benchmark all the things" /></p>
<hr />
Haiku Friday - The Tech Museum of Innovation2014-09-12T00:00:00+00:00http://deonheyns.com/posts/the-tech-museum-of-innovation<p>##Some will always be true geeks
<img src="http://deonheyns.com/images/geek_forever.png" alt="Some will always be true geeks" /></p>
<p>##Visit the Tech Museum you must
<img src="http://deonheyns.com/images/tech_museum.jpg" alt="Visit the Tech Museum you must" /></p>
<p>##To be the ultimate geek
<img src="http://deonheyns.com/images/geek_inside.png" alt="To be the ultimate geek" /></p>
<p>This week’s Haiku was inspired by the awesome Tech Museum of Innovation in San Jose California. Check it out!</p>
<hr />
Transformation Thursday - How do I Check Whether it is DST in Ruby and CSharp?2014-09-11T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-how-do-i-check-dst<p>Today I was playing around with some date and times, I was wondering how could I determine whether daylight savings (DST) was in effect?</p>
<p>So since I am learning Ruby I first tried to do the solution in C# and then Ruby. Here is the C# code.</p>
<script src="https://gist.github.com/DeonHeyns/b04179c9d63d45843035.js"> </script>
<p>Currently, I am in San Jose, California where DST is in effect. In the code above you can see that the there is a static property called ‘Local’ on the ‘TimeZoneInfo’ class that gives us access to an instance of the current time zone as set by Windows. The ‘TimeZoneInfo’ class has a method creatively called ‘IsDaylightSavingTime’ which takes a ‘DateTime’ object and gives an indication whether DST is in effect or not.</p>
<p>To prove that this works I get an instance of the ‘TimeZoneInfo’ class with its time zone set to South Africa Standard Time where I know they don’t have DST.</p>
<p>I output the results of calling ‘IsDaylightSavingTime’ on the instance set to West Pacific Standard Time (California) and on the instance set to ‘South Africa Standard Time’. These calls return true and false which are both correct.</p>
<p>Next let’s do the same using Ruby.</p>
<script src="https://gist.github.com/DeonHeyns/0a7aa223bfc58aefae63.js"> </script>
<p>We ask the ‘Time’ class an instance of the current time and then call the ‘isdst’ method which returns a bool indicating whether or not it is DST. Again to show this is working I change the time zone to ‘Africa/Johannesburg’ and as expected we get the correct results.</p>
<p>Both languages make it simple to determine whether or not DST is in effect. Ruby however does so in fewer keystrokes and to me at least that makes a difference.</p>
<hr />
How To Read a File In Ruby2014-09-10T00:00:00+00:00http://deonheyns.com/posts/how-to-read-a-file-in-ruby<p>I was messing about some more today with files in Ruby today. So I want to read the contents of a file and output it to the screen.</p>
<p>We are going to need to open the file using the ‘open’ method from the Kernel. The ‘open’ method accepts a code block that does the actual reading. To read the contents of the file we will look at a few of the methods available from the ‘IO’ class.</p>
<p>I created a file called shopping.txt, and it contains the following text:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Shopping list
1. Butter
2. Milk
3. Bread
4. Cheese
5. Tomatoes
</code></pre></div></div>
<p>To read all the contents we are going to call the ‘read’ method.</p>
<script src="https://gist.github.com/DeonHeyns/bb2efb928faaeede0f2e.js"> </script>
<p>With this code, we read all the lines of the file into a ‘string’ variable. We then go ahead and print out the class and the contents of the file.</p>
<p>Now let’s say you want an array of strings, an entry for each line in the file. Easy!</p>
<script src="https://gist.github.com/DeonHeyns/461f3571892207b27955.js"> </script>
<p>Instead of calling ‘read’ I called ‘readlines’ and that is it I get an array and do a happy dance. Ruby thanks for making life so awesome!</p>
<hr />
Interacting with the File System2014-09-09T00:00:00+00:00http://deonheyns.com/posts/interacting-with-the-file-system<p>Today I was exploring some of the useful methods <a href="https://www.ruby-lang.org/en/">Ruby</a> has available to work with the File System.</p>
<h2 id="does-my-file-or-directory-exist">Does my file, or directory exist?</h2>
<p>Given that you have a filename or directory name how would you check if it exists? First let’s see how we can check if the file exists? We are going to use the built-in File class in <a href="https://www.ruby-lang.org/en/">Ruby</a> so no need for any require statements.</p>
<script src="https://gist.github.com/DeonHeyns/53148b4770971a47238e.js"> </script>
<p>We see that the File class has a ‘file?’ class method that will return true or false based on whether the file exists or if it doesn’t exist.</p>
<p>Now let’s do the same with a directory.</p>
<script src="https://gist.github.com/DeonHeyns/f5152242737fbb87c92a.js"> </script>
<p>Great, so we can use the same methods that we use to test the existence of a directory to check a file’s existence. However, this is also not so great, reading this code won’t give us any indication that we are checking a file or a directory. A more explicit way of doing this, is by calling the ‘directory?’ method that is also a class level method on File.</p>
<script src="https://gist.github.com/DeonHeyns/d62140dbfb4d9eb695db.js"> </script>
<h2 id="what-sort-of-access-do-i-have-to-a-file-or-directory">What sort of access do I have to a file or directory?</h2>
<p>Next how do we check what sort of access we have on this file. <a href="https://www.ruby-lang.org/en/">Ruby</a> has three different methods that allow us to determine the level of access to a file. These methods are very <a href="https://www.ruby-lang.org/en/">Ruby</a> centric but are still usable across platforms.</p>
<script src="https://gist.github.com/DeonHeyns/3898183994f69d94d9cb.js"> </script>
<p>The methods are pretty straight-forward, call ‘executable?’, ‘readable?’ or ‘writable?’ to get a response on what sort of permission you have on a particular file or directory.</p>
<h2 id="how-do-i-change-the-permissions-of-a-file">How do I change the permissions of a file?</h2>
<p>Now let’s change the permissions on the file. Here are the different Unix permission bits, we are going to use them in this example.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>user_read = 0400
user_write = 0200
user_execute = 0100
group_read = 0040
group_write = 0020
group_execute = 0010
other_read = 0004
other_write = 0002
other_execute = 0001
</code></pre></div></div>
<p>Whilst researching file permissions in <a href="https://www.ruby-lang.org/en/">Ruby</a>, I found that many people suggest creating a class with these various bits as constants. I am going to go ahead and do that as I will never remember these different values.</p>
<script src="https://gist.github.com/DeonHeyns/35288dfe452565a3b346.js"> </script>
<p>We are onto a good thing here. In <a href="https://www.ruby-lang.org/en/">Ruby</a>, we will call the ‘chmod’ method which if you are familiar with Unix changes permissions on files and directories.</p>
<script src="https://gist.github.com/DeonHeyns/30850653161a30ac38ea.js"> </script>
<p>What I found is that the permissions are not additive, meaning if you only set one of the permissions it will only have that permission. So in the case of:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>File.chmod(UnixPermissions::USER_READ, awesome_content)
</code></pre></div></div>
<p>Only read access was available on the file. To set more permissions, you build the permissions using the OR operator (|). So to set the read, write and execute permissions you will need to chain them like so:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>File.chmod(UnixPermissions::USER_READ | UnixPermissions::USER_WRITE | UnixPermissions::USER_WRITE, awesome_content)
</code></pre></div></div>
<p>These are only a handful of the operations available; there is great documentation up at <a href="http://ruby-doc.com/">Ruby-Doc.org</a>. Go ahead and play with some of these methods, sooner or later you are going to need them!</p>
<hr />
Simple Retry Logic When Hitting Exceptions in Ruby2014-09-08T00:00:00+00:00http://deonheyns.com/posts/simple-retry-logic-when-hitting-exceptions-in-ruby<p><a href="/posts/handling-exceptions-in-ruby/">Yesterday</a> I explored how to handle exceptions in <a href="https://www.ruby-lang.org/en/">Ruby</a>. Sometimes though you might want to retry whatever code caused the exception. Take, for instance, the case where your code makes a call out to a Web service. There might be a network outage, and your code is unable to call out or the network is a bit flakey, and you know that after a number of retries your code will be able to reach the Web service.</p>
<p>In typical code you will want to wrap the ‘begin rescue’ or equivalent code in a loop and breakout of the loop after a few iterations if it is not successfully. Let’s take a look at the code that we will be working with.</p>
<script src="https://gist.github.com/DeonHeyns/a29311f6b22ddbb7d1ba.js"> </script>
<p>Running this code will result in an exception being raised when you hit the following line of code:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>resp = Net::HTTP.get_response(URI.parse(url))
</code></pre></div></div>
<p>So we learnt yesterday that we can ensure that the above code won’t come crashing down like a house of cards by wrapping it in a ‘begin rescue’ block. So that is exactly what we are going to do:</p>
<script src="https://gist.github.com/DeonHeyns/0065bbb3c5acc4e297d8.js"> </script>
<p>Great! The code will run now without falling over but what we are missing is some retry logic. Let’s add some logic to try this block of code three times before bailing out:</p>
<script src="https://gist.github.com/DeonHeyns/9838317a6b884db4ec01.js"> </script>
<p>Now we have some code that will run four times and then exit and all the while being graceful about it. What more could a person want? Well isn’t there a way to make this code simpler and easier to understand? Glad you asked because yes there is a way:</p>
<script src="https://gist.github.com/DeonHeyns/d8dcad406c3798c12998.js"> </script>
<p>Ok, what just happened? Well, we got rid of the ‘until’ loop; there is no need for that. A counter called ‘tries’ has been kept to keep track of how many times we have entered the ‘begin’ block. In the rescue block, we make a call to the retry statement that will re-execute the code in the ‘begin’ block whilst our ‘tries’ variable is less than three. The code and approach makes perfect sense, and the code looks great compared to using an ‘until’ loop.</p>
<p>It’s these small things about Ruby that makes it so appealing to me!</p>
<hr />
Handling Exceptions in Ruby2014-09-07T00:00:00+00:00http://deonheyns.com/posts/handling-exceptions-in-ruby<p>Applications that are well-designed handle exceptions and errors to prevent crashes. Exceptions occur when any unexpected or exceptional situations arise whilst a program is running. To handle exceptions a programmer will add specific code to handle the error or exceptional state.</p>
<p>In Ruby, you can use a ‘rescue’ block to recover from an exception or just plain ignore the exception and continue on with the program flow. It is common practice to handle the most specific exception to the most general. This way you can accurately control whatever exceptional event occurred in your code.</p>
<p>Here is a block of code that is going to raise an exception, you can run this in IRB:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">result</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span></code></pre></figure>
<p>This will result in a ZeroDivisonError, in my case this is what displayed in IRB</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ZeroDivisionError: divided by 0
from (irb):3:in `/'
from (irb):3
from /Users/DeonHeyns/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `&lt;main&gt;'
</code></pre></div></div>
<p>So how do I use a ‘rescue’ block to ensure this doesn’t happen? You will want to wrap your code with a ‘begin rescue’ block.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">begin</span>
<span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span>
<span class="k">rescue</span>
<span class="nb">puts</span> <span class="s1">'Hit something here'</span>
<span class="k">end</span></code></pre></figure>
<p>This would handle any exception that might happen in your code, however as I stated earlier it is best practice to handle exceptions from most specific to most general. Enter the following in IRB:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">begin</span>
<span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span>
<span class="k">rescue</span> <span class="no">StandardError</span>
<span class="nb">puts</span> <span class="s1">'StandardError'</span>
<span class="k">rescue</span> <span class="no">ZeroDivisionError</span>
<span class="nb">puts</span> <span class="s1">'ZeroDivisionError'</span>
<span class="k">end</span></code></pre></figure>
<p>Executing this code will result in ‘StandardError’ being printed to the screen. This is because ZeroDivisionError inherits from StandardError resulting in the first block of code being hit.</p>
<p>Let’s swap this code around this time and see the difference.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">begin</span>
<span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span>
<span class="k">rescue</span> <span class="no">ZeroDivisionError</span>
<span class="nb">puts</span> <span class="s1">'ZeroDivisionError'</span>
<span class="k">rescue</span> <span class="no">StandardError</span>
<span class="nb">puts</span> <span class="s1">'StandardError'</span>
<span class="k">end</span></code></pre></figure>
<p>This results in ‘ZeroDivisionError’ showing up on the screen and that is exactly what we need, we can now handle the most specific error and the more general thereafter. Don’t believe this is the case? Let’s do another quick test. Go ahead and enter the following code in your IRB session.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">begin</span>
<span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span>
<span class="k">rescue</span> <span class="no">LoadError</span>
<span class="nb">puts</span> <span class="s1">'LoadError'</span>
<span class="k">rescue</span> <span class="no">ZeroDivisionError</span>
<span class="nb">puts</span> <span class="s1">'ZeroDivisionError'</span>
<span class="k">rescue</span> <span class="no">StandardError</span>
<span class="nb">puts</span> <span class="s1">'StandardError'</span>
<span class="k">end</span></code></pre></figure>
<p>The result? The result is that ‘ZeroDivisionError’ is printed to the screen, this proves that the most specific rescue block is hit and if not then the most general rescue block will be hit.</p>
<p>Ruby exception handling is very similar to most other programming languages. If you know that a piece of code is going to raise an exception, you can wrap that code in a ‘begin rescue’ block to ensure that your application does not exit and cause your user to rage.</p>
<hr />
JSON Serializer not Required2014-09-06T00:00:00+00:00http://deonheyns.com/posts/json-serializer-not-required<p>Today was spent driving around the Bay Area taking in some of the sites and sounds. All the driving I did today means I got very little Ruby coding done today. I did however find some magic; I found the JSON library that is part of the Ruby Standard Library.</p>
<p>You might be asking so what? Well to me this is amazing, there are many third-party JSON serializers in the .NET world and there is the built-in JavaScriptSerializer. However, there is nothing that just works, nothing that makes it so simple that you could remember the complete syntax and never need to Google it.</p>
<p>In Ruby, there is just such a library a library that can do all the JSON work that you actually need to be done. Something that is powerful, yet simple. Ruby is very much geared toward developer productivity and happiness. The JSON library is a library that will make you feel good!</p>
<p>What is JSON? JavaScript Object Notation (JSON) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition.</p>
<p>So want to know how you can use the JSON library? As usual when it comes to Ruby quite easily. Here is some code taking a random Hash and converting it to JSON:</p>
<script src="https://gist.github.com/DeonHeyns/8ed454c28059c5f2e2b1.js"> </script>
<p>This bit of code results in:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{"userId":1,"title":"Yo my people","body":"Lorem Ipsum"}
</code></pre></div></div>
<p>To me I am blown away; all I need to do to get out a JSON object is create a Hash with some keys, call JSON.generate and go sip some cocktails? Really? Is there some trick? There must be magic going on here. Nope, just regular well thought-out Ruby that makes somebody’s life easier.</p>
<p>I like Ruby its a great language, it’s the small things like the JSON library that give it a massive edge over other programming languages and their ways.</p>
<hr />
Haiku Friday - Save the Drama For Yo Mama Round 22014-09-05T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-save-the-drama-for-yo-mama-round-2<p>##We no longer have Joan
<img src="http://deonheyns.com/images/joan_rivers_rip.jpg" alt="RIP Joan Rivers" /></p>
<p>##Still we want drama every day…
<img src="http://deonheyns.com/images/drama.gif" alt="Still we want drama every day..." /></p>
<p>##Well we still have Markdown
<img src="http://deonheyns.com/images/coding_horror.png" alt="Well we still have Markdown" /> vs <img src="http://deonheyns.com/images/john_gruber.png" alt="Well we still have Markdown" /></p>
<p>This week’s Haiku is inspired by the ridiculous and unnecessary drama between Jeff Atwood (<a href="https://twitter.com/codinghorror">@codinghorror</a>) and John Gruber (<a href="https://twitter.com/gruber">@gruber</a>)</p>
<hr />
And Now Some Sparklines2014-09-04T00:00:00+00:00http://deonheyns.com/posts/and-now-some-sparklines<p><a href="/posts/creating-graphs-in-ruby/">Yesterday</a> I wrote about creating graphs in Ruby using the Gruff gem. While I was researching the Gruff gem, I came across another library written by Geoffrey Grosenbach called <a href="https://github.com/topfunky/sparklines">Sparklines</a>.</p>
<p>A sparkline is a tiny graph; it’s often drawn without an axis. It shows the general shape of some plottable data. Most commonly you will find Sparklines used to chart temperatures or stock market price. Sparklines are usually embedded in a piece of text, and it is not uncommon for Sparklines to be grouped together as a panel chart.</p>
<p>The term sparkline was coined by Edward Tufte for “small, high resolution graphics embedded in a context of words, numbers, images”. Sparklines can be described as “data-intense, design-simple, word-sized graphics”.</p>
<p>Will often see Sparklines used on sites similar to the <a href="http://online.wsj.com/home-page?refresh=on">WSJ</a> to convey a message about stocks or the economy.</p>
<p>So enough history on Sparklines, let’s write some code that will display the Google stock price for the last six months.</p>
<p>Great so first we are going to need some data, just as we did yesterday we are going to use Yahoo Finance and download the historical stock price for Google for the last six months. I downloaded the file and kept the default name of ‘table.csv’.</p>
<p>As always we are going to need to install a gem, so add the ‘sparklines’ gem to your Gemfile or run the command ‘gem install sparklines’</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem 'sparklines'
</code></pre></div></div>
<p>Here is the complete code.</p>
<script src="https://gist.github.com/DeonHeyns/a30f8a1b41925c081de4.js"> </script>
<p>In our Ruby file we are going to need three require statements one for ‘csv’, another for ‘sparklines’ and the last one is for ‘base64’. We are going to read the ‘table.csv’ so therefore we need the require to ‘csv’, we are obviously going to display our data as a Sparklines hence the reference to ‘sparklines’ and lastly we are going to embed our Sparkline in an HTML page since it looks much better than saving it to a file.</p>
<p>The code is very straightforward, the real logic starts happening at line 19, the rest of the code is just plumbing. So using CSV we read out the data from the CSV file, we get the closing stock price for each day by using the ‘collect’ method.</p>
<p>A call to ‘generate_sparkline’ is made which in turns calls the Sparklines ‘plot’ method that takes in the data and options that can be set on the Sparkline. The ‘plot’ method returns the binary data for our Sparkline. Since we are embedding this Sparkline in an HTML page, we go ahead and create an ‘img’ tag and set the ‘src’ attribute equal to the BASE64 representation of our binary data.</p>
<p>Once we have done all of this we can go ahead and write this ‘img’ tag to an HTML file using built-in functionality in Ruby.</p>
<p>The result of this is:</p>
<p>NYSE: GOOG (<img src="http://deonheyns.com/images/google.png" alt="google" />) Closing Stock Price</p>
<p>Pretty neat right? I think this is great, and there are a lot more things possible with this library like changing the color, using a bar chart, etc. I encourage you to check the <a href="https://github.com/topfunky/sparklines">library</a> out and play with it! One thing I will say is that the library is very old, there are still 5 open issues on GitHub but for the most part I think the library is stable and quite possibly it is done.</p>
<hr />
Creating Graphs in Ruby2014-09-03T00:00:00+00:00http://deonheyns.com/posts/creating-graphs-in-ruby<p>I have been working in the Financial services industry for over nine years. In that time I have found that at some or other point you are going to be asked to create a line, bar or pie chart. So today I was investigating how to do this with Ruby. If we are going to be creating charts for a Web application, according to The Ruby Toolbox <a href="http://chartkick.com/">Chartkick</a> is the favorite. However in my case I just want to create some simple PNGs, so I am going to use <a href="https://github.com/topfunky/gruff">Gruff</a>.</p>
<p><a href="https://github.com/topfunky/gruff">Gruff</a> created by Geoffrey Grosenbach has a tag-line of ‘Beautiful graphs for one or multiple datasets. Can be used on websites or in documents.’ So let’s test that out and create some charts.</p>
<p>First we are going to need some test data, I went and pulled down Google’s stock performance for the last six months or so. To get this data just use Yahoo finance they have a nice export to Spreadsheet button that give you the stock information in a CSV. To get to the historical data just hit http://finance.yahoo.com/q/hp?s=GOOG.</p>
<p>So the requirement for today is simple, show the Open, High, Low and Close prices for Google’s stock on a line chart.</p>
<p>Firstly you are going to need the ‘<a href="https://github.com/topfunky/gruff">Gruff</a>’ library, if you have a Gemfile then just add the following line to your Gemfile:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem 'gruff'
</code></pre></div></div>
<p>Alternatively just install the gem via the command-line:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem install gruff
</code></pre></div></div>
<p>Here is the full code listing, we will go through the majors parts below:</p>
<script src="https://gist.github.com/DeonHeyns/6ed19d8be317d9afee4d.js"> </script>
<p>In our code, we need two require statements. One will be for the <a href="https://github.com/topfunky/gruff">Gruff</a> gem, and another will be for CSV. Since we are reading the stock information from a CSV, we can use Ruby’s built-in library to parse our document.</p>
<p>At line four we assign the contents of our CSV file to a variable called google, since our CSV contains a header on the first line we make sure to let Ruby know that this is the case.</p>
<p>Next is some boilerplate code to create our graph with a width of 600 pixels and we set the header on the chart.</p>
<p>The x-axis of our Line chart is going to be the trading dates. We call the ‘foreach’ method on the CSV and pull out all the trade dates. To get the start date of our dataset we call the ‘min’ method on the array of dates. For the “middle” date, we do some simple Math to get the date that is in the middle of the start and end dates. Lastly for the end date of our dataset we again just call ‘last’ which gets the last element in the array.</p>
<p>Then we are ready to set the labels property on our graph object, we set the property to a Hash of keys and dates. The labels property will then be displayed as our x-axis.</p>
<p>For each line on our Line chart, we need to pass in the label as well as the data series. Since we are looking for Open, High, Low and Close that is the labels we pass through as well as the corresponding data associated.</p>
<p>I go ahead and set some meaningful labels on the x and y axis, thereafter to create the chart we call the write method passing in the path with the file extension to where the image of the chart needs to be save.</p>
<p>All of this will output this image:</p>
<p><img src="http://deonheyns.com/images/google_stock.png" alt="Stock" /></p>
<p>Pretty cool right? There wasn’t much involved in getting this working there are numerous other charts available in <a href="https://github.com/topfunky/gruff">Gruff</a>, should you be interested I recommend checking out the repository on GitHub and playing with the library.</p>
<hr />
How do I go from String to Symbol and Symbol to String?2014-09-02T00:00:00+00:00http://deonheyns.com/posts/how-do-i-go-from-string-to-symbol-and-symbol-to-string<p>A Symbol is a very basic Ruby Object; it is just a name, and an internal ID. Symbols are great as keys in a Hash. What you should also remember is that Symbols refer to the same Object throughout a Ruby program. Two strings with the same contents are two different Objects, whereas at any given time there is only one instance of a Symbol. This is very good for memory usage, and it is also quicker to compare two Symbols then comparing two strings, this is because when it comes to Symbols Ruby only compares the IDs of the Objects.</p>
<p>So how do you go about converting a String to a Symbol and vice versa? Easy, as usual with Ruby there are methods that quickly take you from one type to the next.</p>
<script src="https://gist.github.com/DeonHeyns/b3dd8977161bdcc6803f.js"> </script>
<p>Ruby exposes the ‘to_s’ method on the Symbol to convert it to a string; the String class has a method called ‘to_sym’ that converts a string to a Symbol.</p>
<p>As you can see in lines 8 and 9 a symbol always has the same object ID and, therefore, we can reason that there is only ever one instance of the Symbol. Now compare that to the String class, the same string representation is two different instances and therefore means more memory usage.</p>
<p>Jim Weirich famously said:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>I (generally) use the following rule on string vs. symbols:
(1) If the contents (i.e. the sequence of characters) of the object is important, use a String.
(2) If the identity of the object is important, use a Symbol.
</code></pre></div></div>
<p>That makes it quite clear when to pick a String and when to pick a Symbol. Happy coding people!</p>
<hr />
Reversing Strings in Ruby2014-09-01T00:00:00+00:00http://deonheyns.com/posts/reversing-strings-in-ruby<p>Let’s say you have a string, the words in the string are in reverse order, you know what even the letters are reversed. Now you need to correct this order, how would you do this? In Ruby, you have a few methods that help you do this that you don’t need to go and loop over your string and fix the order. First let’s do this the hard way by writing all the code to do the looping and ordering.</p>
<script src="https://gist.github.com/DeonHeyns/8decf304b5494bd838c6.js"> </script>
<p>In this code, we loop over the string in reverse. Each character is appended by accessing it by index. We use a variable ‘i’ as an indexer that is used to evaluate whether we have iterated through the whole length of our string that is incorrect. If there is one thing I have learned about while loops is that they are susceptible to Stack Overflows, I, therefore, tend to stay away from them at all costs.</p>
<p>So how could we write this code without using a loop and with only using the built-in Ruby methods? Enter the reverse method. Reverse returns a new string with the characters from a string in reverse order. So all we need to do to get the same result is call reverse.</p>
<p>Here is the code:</p>
<script src="https://gist.github.com/DeonHeyns/c22fcd2949113e86d8ca.js"> </script>
<p>How awesome is that? Pretty cool right. Let’s try something a bit different, what if our words were not in reverse but the sentence was? Let’s take the string ‘reads. sentence this way the is This’, if we were to call reverse it will result in ‘sihT si eht yaw siht ecnetnes .sdaer’. This is obviously totally wrong but fear not, with a few more built-in methods we can correct this.</p>
<script src="https://gist.github.com/DeonHeyns/9e7597fe5971639e4c74.js"> </script>
<p>We go ahead and convert the string to an array called string_array by splitting it by whitespace. Next up we call reverse on string_array that we have just created, doing this puts our words in the correct order in our array. We then call join and pass in whitespace to ensure our string is separated by whitespace and hey presto we have a string that is in the correct order once again.</p>
<p>This was all pretty straight-forward and saved us from using a bunch of loops that will cause headaches at some or other time. Ruby is very expressive and rolls off the tongue like a spoken language. Ruby is fun and full of great features that make a developer’s life easier!</p>
<hr />
Using REXML to Parse XML Documents2014-08-31T00:00:00+00:00http://deonheyns.com/posts/using-rexml-to-parse-xml-documents<p><a href="/posts/using-nokogiri-to-parse-xml-documents/">Yesterday</a> I wrote about using <a href="http://nokogiri.org/">Nokogiri</a> to parse the XML file that contains a purchase order to retrieve details about the Shipping address. Today I thought I would go ahead and do the same exercise using <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a>.</p>
<p>Here is the description of <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a>:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>REXML is a pure Ruby, XML 1.0 conforming, non-validating toolkit with an intuitive API.
REXML passes 100% of the non-validating Oasis tests, and provides tree, stream, SAX2,
pull, and lightweight APIs. REXML also includes a full XPath 1.0 implementation.
Since Ruby 1.8, REXML is included in the standard Ruby distribution.
</code></pre></div></div>
<p>So <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a> is included in the Standard library and is most probably used by all the other <a href="https://www.ruby-lang.org/en/">Ruby</a> XML libraries. <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a> was inspired by the Electric XML library for Java, which has an easy-to-use API, it’s small size and is quite fast. <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a> was designed with the same philosophy as Electric XML and has these same features.</p>
<p><a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a> supports both tree and stream document parsing. Stream parsing is about 1.5 times faster. However, with stream parsing, you don’t get access to features such as XPath.</p>
<p>We will use the same document that I used in the previous post on parsing XML. To remind you of the document we are parsing here it is:</p>
<script src="https://gist.github.com/DeonHeyns/7f8eb73d234db4c810a9.js"> </script>
<p>Our requirement is simple, pullout the shipping address and display the name, street, city, state, zip and country.</p>
<script src="https://gist.github.com/DeonHeyns/2345e2d1e34acf9082fb.js"> </script>
<p>Since <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a> is included in the <a href="https://www.ruby-lang.org/en/">Ruby</a> Standard Library, there is no need to install any gems, you still need to require ‘<a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">rexml</a>/document’ to parse the file through. In the code, I use the ‘include <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a>’ directive for easy of use. The ‘purchase_order.xml’ file will be read into memory and is accessible via the file variable.</p>
<p>To get access to the XML document, I create a new instance of the Document class passing in the contents of the ‘purchase_order.xml.’ file.</p>
<p>Just as I done with <a href="http://nokogiri.org/">Nokogiri</a> I pullout the Shipping address using the XPath expression</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/PurchaseOrder/Address[@Type='Shipping']
</code></pre></div></div>
<p>Unlike <a href="http://nokogiri.org/">Nokogiri</a>, I read all the details I need to display the name, street, city, state, zip and country of the Shipping address using the map method. Then we can display these details using the ‘puts’ method.</p>
<p><a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a> is easy to use and comes bundled in the Standard Library; therefore, it would be my first choice when it comes to parsing XML. Having stated that I still feel <a href="https://github.com/jnunemaker/crack">Crack</a> had the best API for my needs and felt a lot more easy to use compared to <a href="http://nokogiri.org/">Nokogiri</a> and <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/rexml/rdoc/REXML.html">REXML</a>.</p>
<hr />
Using Nokogiri to Parse XML Documents2014-08-30T00:00:00+00:00http://deonheyns.com/posts/using-nokogiri-to-parse-xml-documents<p><a href="/posts/transformation-thursday-reading-xml-in-csharp-vs-ruby/">The other day I needed to parse some XML</a>, I used <a href="https://github.com/jnunemaker/crack">Crack</a>, which is a great library, but wanted to checkout what other libraries I could use. Today going through The Ruby Toolbox I came across <a href="http://nokogiri.org/">Nokogiri</a>, which is a widely used library.</p>
<p>Straight from the <a href="http://nokogiri.org/">Nokogiri</a> site:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Nokogiri (鋸) is an HTML, XML, SAX, and Reader parser. Among Nokogiri’s many features is the ability to search documents via XPath or CSS3 selectors.
</code></pre></div></div>
<p><a href="http://nokogiri.org/">Nokogiri</a> seems much better suited to parsing HTML. <a href="http://nokogiri.org/">Nokogiri</a> has methods that make it easy to select elements using CSS3 selectors. For parsing XML <a href="http://nokogiri.org/">Nokogiri</a> gives you access to the document via XPath. I have never been a big fan of XPath; it does simplify accessing elements in an XML file, but it’s still not my favorite.</p>
<p>Enough talk let’s parse an XML document. We will use the same document that I used in the previous post on parsing XML. To remind you of the document we are parsing here it is:</p>
<script src="https://gist.github.com/DeonHeyns/7f8eb73d234db4c810a9.js"> </script>
<p>Our requirement is simple, pull out the shipping address and display the name, street, city, state, zip and country.</p>
<p>Now <a href="http://nokogiri.org/">Nokogiri</a> needs a few supporting libraries so you will most probably need to install libxml2 and libxslt. The easiest way to install both libxml2 and libxslt is to use Homebrew. There are numerous tutorials to install Homebrew, use one of those if you don’t have it installed yet.</p>
<p>Once you have libxml2 and libxslt, you can install <a href="http://nokogiri.org/">Nokogiri</a> by adding it to your gemfile or install the gem</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem install nokogiri
</code></pre></div></div>
<p>Here is the code to parse the XML and pullout the details we need:</p>
<script src="https://gist.github.com/DeonHeyns/eb4d4b4c5841b5e7ae82.js"> </script>
<p>Firstly we read the XML file into a variable and use <a href="http://nokogiri.org/">Nokogiri</a> to parse the XML document. To get our Shipping address we use the XPath query:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/PurchaseOrder/Address[@Type='Shipping']
</code></pre></div></div>
<p>That says, “Looking for the Address with a Type of Shipping under PurchaseOrder.” We then have the XML fragment necessary to get to the name, street, city, state, zip and country elements. We can get to these elements by using another XPath to each element and calling ‘text()’ to get to the values. By putting all the elements, we care about into a ‘details’ variable we can call the put method to print the results to the screen.</p>
<p>As I said earlier, <a href="http://nokogiri.org/">Nokogiri</a> seems to be better-suited at parsing HTML give its CSS3 selectors. I am not a big fan of XPath so if I were to choose which library to use I would much rather use <a href="https://github.com/jnunemaker/crack">Crack</a> then <a href="http://nokogiri.org/">Nokogiri</a>.</p>
<hr />
Haiku Friday - Surviving APIs With Rails2014-08-29T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-surviving-apis-with-rails<p>##Write APIs in Rails
<img src="http://deonheyns.com/images/love_apis.png" alt="I love APIs" /></p>
<p>##A path to your happiness
<img src="http://deonheyns.com/images/finding-happiness-in-recovery.jpg" alt="happiness" /></p>
<p>##Includes an IPA
<img src="http://deonheyns.com/images/APIs-and-IPAs-PDX.png" alt="One blogpost a day" /></p>
<p>This week I spent some time working with Rails APIs and XML…</p>
<hr />
Transformation Thursday - C# to Ruby, Reading XML in C# vs Ruby2014-08-28T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-reading-xml-in-csharp-vs-ruby<p>This week I needed to parse a massive XML file. In the corporate world, XML is the defacto standard for systems to communicate with each other. In C#, we have a few ways to parse XML the easiest being using LINQ to XML or creating a class and using the XmlSerializer to parse the XML. C# has another way to read XML using Xpath but in the .NET world it is far simpler to just use the aforementioned techniques. In Ruby you just need to head to The Ruby Toolbox, search for XML and be overwhelmed by the different libraries.</p>
<p>For our discussion, today let’s assume that our XML structure looks as follows:</p>
<script src="https://gist.github.com/DeonHeyns/7f8eb73d234db4c810a9.js"> </script>
<p>Look at that, nothing like some XML! Our requirement here is to pull out the shipping address and display the name, street, city, state, zip and country. I’m going to use LINQ to XML in this example because it is the closest to what you would do in Ruby.</p>
<script src="https://gist.github.com/DeonHeyns/59d9d20b3c7c35fd4f7f.js"> </script>
<p>Looking at the code I am quite happy at the result. We are obviously using LINQ to XML, so we need the two references to System.Linq and System.Linq.Xml. We first load the ‘purchase_order.xml’ file from disk and read it into a variable called root. Using LINQ we query the root variable’s Elements and get all the ‘Address’ nodes / elements. Once we have all the ‘Address’ nodes, we go ahead and constrain that down to just the Billing address by doing a comparison on the Type attribute to the string value of ‘Billing’. After we have queried our root variable, we can now access the necessary elements to display the name, street, city, state, zip and country values of the address. The code is straightforward and easy to read. I have no complaints about this code, and yes I know there is null handling code present.</p>
<p>Let’s compare this to what is available in Ruby. First we are going to need the Crack gem, so gem install that bad boy or place the following in your gemfile:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem 'crack'
</code></pre></div></div>
<p>Now let’s write the code:</p>
<script src="https://gist.github.com/DeonHeyns/d76b149f5b04a24234ee.js"> </script>
<p>So since we are using a third-party gem we need a require to the Crack library, since we are using the XML parsing functionality we also need to require ‘crack/xml’. Now that we are setup with the library necessary to parse XML we can start with our plumbing. We have a ‘purchase_order’ variable that holds the parsed XML document. The cool thing about Crack is that it parses your XML into a Hash, this means everything is available to you via simple name value pairs. To get our billing address we are going to use the Ruby find method, the find method takes a block that will be used to find what you are looking for. We put the billing address we searched for into the billing_address variable. At this point, we can use simple string interpolation to pull out the name, street, city, state, zip and country values. Last but not least we use the puts method to print the details to the screen.</p>
<p>Both languages make parsing XML quite simple. I like the Ruby way, you don’t need to mess about with attributes or elements or any other nonsense, you are given a Hash and iterate or access the values as needed. There you go if you need to parse XML in C# or Ruby or just needed a quick comparison there you go.</p>
<hr />
What the Proc is a Proc?2014-08-27T00:00:00+00:00http://deonheyns.com/posts/what-the-proc-is-a-proc<p>Today I was reading some C# code that passed around delegates. Delegates are analogous to function pointers. Thus, delegates allow you to pass around methods. So how does one accomplish this in Ruby? Well, pretty simple, you use a Proc object.</p>
<p>Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables. Procs encapsulate behavior, so you can use a Proc as a callback. A callback is invoked when a particular event happens, and the callback function will be called, and this notifies your code that something of interest has taken place. This can be very useful in logging or in an eventing system where you want some logic to be triggered once something happens</p>
<p>Let’s say for instance we want ‘Awesome’ to be printed whenever something cool happens in our database code. First thing we would do is create a method that will print out ‘Awesome’ like so</p>
<script src="https://gist.github.com/DeonHeyns/55c4d0a0201f25402a9c.js"> </script>
<p>Next we will write the code that is going to use this method, we also invoke the Proc by using the call method.</p>
<script src="https://gist.github.com/DeonHeyns/7cba1bae0ef125924fd9.js"> </script>
<p>Doing this you will see ‘Awesome’ printed to your screen, fairly boring but we can make it more exciting.</p>
<p>Next let’s create a method that will take in the Proc and execute it. We are going to use the ‘&amp;block’ syntax to pass in our Proc, using a ‘&amp;block’ will also allow us to pass in a block of code and run it.</p>
<p>Here is my quick explanation of what is the difference between a Proc and a block. A Proc is an object whereas a block is an anonymous function.</p>
<p>Here is our method:</p>
<script src="https://gist.github.com/DeonHeyns/004df05262ed8ff4eef8.js"> </script>
<p>Now we can call our method passing in our Proc.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>some_call(&amp;proc)
</code></pre></div></div>
<p>Calling our method passing in our earlier defined Proc object will result in ‘Awesome’ being printed to the screen. We can also call the ‘some_call’ method with a block.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>some_call do
puts 'Juice'
end
</code></pre></div></div>
<p>This will result in ‘Juice’ printed to the screen.</p>
<p>The Proc object is pretty powerful, it is pretty straightforward to use, and there are numerous uses for it. Just think of Proc as a function pointer or as a delegate, and you will have a good idea how it works.</p>
<hr />
Ruby Does My Regex not Match2014-08-26T00:00:00+00:00http://deonheyns.com/posts/ruby-does-my-regex-not-match<p>Since learning Ruby, I have had to become comfortable with using the command line, the syntax and regex. I am not a big fan of regex, since working on C# I can single handily count how many regexes I have written. In the Ruby world, however, authoring regexes is part and parcel of everyday life.</p>
<p>Tonight I was playing around with my regexes but couldn’t find a way for Ruby to tell me when it couldn’t find a file that was asked for.</p>
<p>Tonight I found this of code that I hope will go a long way in solving my needs. This code will tell you whether or not a string value matches what is used in a regex.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>'x' !~ /x/
</code></pre></div></div>
<p>This is awesome. With a simple regex, I am able to get a lot of mileage out of the code I have written.</p>
<p>This is an exciting time for me and what better time to write some good rock-solid code.</p>
<p>I was also super tired writing this, so if none of this makes sense I appologies.</p>
<hr />
Some handy HTTP Status codes to remember2014-08-25T00:00:00+00:00http://deonheyns.com/posts/some-handy-http-status-codes-to-remember<p>I usually forget the different HTTP Status codes. In an effort to have some place they are available, I am posting them here.</p>
<p>###Success codes:</p>
<p>200 - OK (the default)</p>
<p>201 - Created</p>
<p>202 - Accepted (often used for delete requests)</p>
<p>###User error codes:</p>
<p>400 - Bad Request (generic user error/bad data)</p>
<p>401 - Unauthorized (this area requires you to log in)</p>
<p>404 - Not Found (bad URL)</p>
<p>405 - Method Not Allowed (wrong HTTP method)</p>
<p>409 - Conflict (i.e. trying to create the same resource with a PUT request)</p>
<p>Should you need to test out different HTTP Status codes I highly recommend <a href="http://httpstatus.es/">httpstatus.es</a> and here is another <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">resource</a>.</p>
<p>REST has been made overly complicated by some. Sometimes you just need to know what are the main status codes, so hopefully you will bookmark this page and refer to it whenever you get stuck on an HTTP Status.</p>
<hr />
Database Migrations Converting DbScriptomate to Ruby - Fixing Something I Don't Like2014-08-24T00:00:00+00:00http://deonheyns.com/posts/database-migrations-converting-dbscriptomate-to-ruby-fixing-something-i-don't-like<p>Yesterday we saw this code that will run the SQL scripts that are passed to it:</p>
<script src="https://gist.github.com/DeonHeyns/18dfeecdf57581f4f9e1.js"> </script>
<p>I don’t like it! The method signature looks as if it will only grow and why are there readable attributes set, who is going to need the SQL Server specific username, password, host and database?</p>
<p>If we look at the creation of the new TinyTDS Client class, we get a hint on how to clean this code up. If we were to pass in an options Hash we could make our life a lot easier, so let’s do that.</p>
<script src="https://gist.github.com/DeonHeyns/a076b420890783a49969.js"> </script>
<p>In this code, we are passing in an options Hash, and this is used in the call to our TinyTDS class, it just looks better. The initialize method does not look a bunch better, but it’s getting there.</p>
<p>Let’s make another change. I said earlier that we no longer needed the readable attributes so let’s get rid of that code.</p>
<script src="https://gist.github.com/DeonHeyns/fd3b2a4dfaa082fb005b.js"> </script>
<p>That feels much better; there is a lot less noise going on in this class. Now the SqlServerRunner is just a thin wrapper over TinyTDS.</p>
<p>So how does this affect our Command class? Well, we can simplify the execute method that is part of the Command class and make it a lot easier on the lines. Here is how the code looks before we refactor it.</p>
<script src="https://gist.github.com/DeonHeyns/cdd8c91dc4f8e1f0bf98.js"> </script>
<p>Now after the refactor the code looks better.</p>
<script src="https://gist.github.com/DeonHeyns/f6496db1d8f439f42c4e.js"> </script>
<p>We only got rid of a few lines of code but the good thing is our code is a little better. Something a lot of developers tend to forget is that refactoring doesn’t need to be an exercise in mimicking a tornado, you don’t need to come in and drastically change everything. Small, thoughtful changes will do the job. Your team will be much happier with small incremental changes and the guy that does a peer / code review will also be happy that he isn’t confronted by a wall of red and green when they open your pull request.</p>
<hr />
Database Migrations Converting DbScriptomate to Ruby Running our SQL Scripts2014-08-23T00:00:00+00:00http://deonheyns.com/posts/database-migrations-converting-dbscriptomate-to-ruby-running-our-sql-scripts<p>So last time I posted on the DbScriptomate migration it was about a spike I done to get SQL Server and Ruby talking to each other. Tonight I got time to implement the code. We are now able to run scripts against our database!</p>
<p>Let’s see how this is done. Firstly I created a new class that will interact with TinyTDS called SqlServerRunner. The constructor is then passed the username, password, host and database. These parameters are used to create our TinyTDS connection that will be used to do the heavy work of interacting with SQL Server.</p>
<p>Here is the code to implement the SqlServerRunner class:</p>
<script src="https://gist.github.com/DeonHeyns/29d310c6d730c9a9942d.js"> </script>
<p>Next we are going to add a new method to our SqlServerRunner called run_sql. The run_sql method will take a string that will be our SQL to run. This can be any valid SQL, and it will be executed against the database that was pass through the command line. The run_sql method makes a single call to execute which is part of TinyTDS.</p>
<script src="https://gist.github.com/DeonHeyns/18dfeecdf57581f4f9e1.js"> </script>
<p>So far so good nothing to great about this code, all this code does is hide us from TinyTDS.</p>
<p>Next up we are going to edit our Command class. The Command class is the main orchestrator of DbScriptomate; it will do the directing of traffic so to speak. We can add a new method to the Command class called execute, execute will take an array of file paths, read the contents which is SQL and put that in an array for later. Next we are going to create an instance of the SqlServerRunner class and pass to it the necessary arguments to create an instance. We can now loop through the array that contains the SQL and call the run_sql method from SqlServerRunner. This will go ahead and execute the SQL scripts one by one against the DB.</p>
<p>The code for the execute method is pretty simple:</p>
<script src="https://gist.github.com/DeonHeyns/cdd8c91dc4f8e1f0bf98.js"> </script>
<p>Here is the full listing of the command.rb file with the new code to run the SQL files.</p>
<script src="https://gist.github.com/DeonHeyns/c3a78c6c47a63b3b377a.js"> </script>
<p>You can again see how easy Ruby makes our lives. I wrote this code in about 5 minutes, and it is working perfectly for my needs. We are at a good place now and have an excellent foundation. There is still some work to do but in my next post I would like to write some tests and talk about refactoring this code.</p>
<hr />
Haiku Friday - Zombies Now Teach Rails?2014-08-22T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-zombies-now-teach-rails<p>##Zombies They Eat Brains
<img src="http://deonheyns.com/images/brains.jpg" alt="zombies they eat brains" /></p>
<p>##If The Zombies Are From Code School
<img src="http://deonheyns.com/images/code_school.png" alt="if the zombies are from code school" /></p>
<p>##You Grow A Brain or Two
<img src="http://deonheyns.com/images/raptor.jpg" alt="raptor" /></p>
<p>This week’s lame-o Haiku was inspired by the teaching style of <a href="https://www.codeschool.com/">Code School</a></p>
<hr />
Transformation Thursday - C# to Ruby, How to create a MD5 Hash2014-08-21T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-csharp-to-ruby-How-to-create-a-md5-hash<p>Earlier this week I revisited some code in our code base that hashes a password. I done some investigation how to do this via C# and Ruby. Let’s firstly remind ourselves where MD5 hashing comes from and what it is.</p>
<p>MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4. The MD5 message-digest algorithm is a widely used cryptographic hash function producing a 128-bit (16-byte) hash value, typically expressed in text format as a 32 digit hexadecimal number. MD5 has been utilized in a wide variety of cryptographic applications and is also commonly used to verify data integrity.</p>
<p>So you could use an MD5 hash on the contents of a file to check if anything changed on it, or use it to hash a string. You however would want to use something stronger than MD5 if you need to hash and store passwords.</p>
<p>So how do you do this in C#:</p>
<script src="https://gist.github.com/DeonHeyns/2293d9c12cbc3c3076db.js"> </script>
<p>So firstly what you don’t see from this code is the two using statements we need.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>using System.Text;
using System.Security.Cryptography;
</code></pre></div></div>
<p>Without those two using statements, the StringBuilder class and MD5 class would just moan. First thing we do is create a new MD5 class using the Create factory method. Next we ensure we get the byte value of the string we are hashing. We can then compute the hash passing in the byte array we get from the string. The next few lines loop over our MD5 hash byte array and converts each item into a lowercase hexadecimal character. Nice from that we have our hash and can do whatever we want.</p>
<p>Next up is the Ruby implementation, are you ready for this? Well, okay here goes:</p>
<script src="https://gist.github.com/DeonHeyns/01ee4c60aa544b8e0680.js"> </script>
<p><img src="http://deonheyns.com/images/bam!.gif" alt="Bam drops mic" /></p>
<p>That’s me I am done here.</p>
<hr />
First Open Bermuda Meet-up2014-08-20T00:00:00+00:00http://deonheyns.com/posts/first-open-bermuda-meet-up<p>A quick post. Tonight was the first ever Open Bermuda meeting held at the Bermuda Chamber of Commerce. The attendance far exceeded my expectations. There were people there with various backgrounds, some developers and some not. John Gill, the organizer, done a great job of getting beers and pizzas for everyone and by everyone I mean over 20 people.</p>
<p>The meeting started with John telling us how and why he decided to start the group. John then told us about his history with open source and how he envisions the meetings going forward. There were a lot of passionate people, and everyone had the opportunity to do a lighting talk on what they wanted to gain from these meet-ups. I mustered up the courage and gave a brief history of myself and what I wanted to gain from the group.</p>
<p>What became very evident from tonight’s meet-up is, this is going to be language agnostic. Bermuda is too small for this group just to be about Python or .NET or Ruby. I am excited by this fact and hope to do a presentation about Ruby at the group in a few weeks time.</p>
<p>Its a very exciting time to be a developer and clearly the tech community in Bermuda wants a place to meet and share ideas and collaborate. I left the group tonight with a good feeling; we have a great foundation to build on, and I can only see the group going from strength to strength.</p>
<p>Tomorrow we are back to Ruby and specifically how you do MD5 hashing in C# vs. Ruby.</p>
<hr />
Update - My Progress on the Path to Learning Ruby2014-08-19T00:00:00+00:00http://deonheyns.com/posts/update-my-progress-on-the-path-to-learning-ruby-and-rails<p>If you have been reading my blog posts, you will know that I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby/">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> and <a href="http://rubyonrails.org/">Rails</a>. I created a plan a few weeks back and thought it was a good time to give a progress update on how my learning is going.</p>
<p>So firstly since my last update here is what I have done or am busy with, and we can dig deeper into these items:</p>
<ul>
<li><a href="/posts/an-introduction-to-rails-ruby-on-rails-tutorial/">Rails Tutorial by Michael Hartl</a></li>
<li><a href="/posts/railscasts-another-awesome-resource-for-rails-and-ruby/">Railscasts by Ryan Bates each day</a></li>
<li><a href="/posts/a-journey-on-sending-emails-the-conclusion/">Series of posts on email libraries available in Ruby and when to use which</a></li>
<li><a href="/posts/codeschool-they-finally-have-my-money/">Code School</a></li>
<li><a href="/posts/database-migrations-converting-dbscriptomate-to-ruby/">Rewrite of a C# project to Ruby</a></li>
<li><a href="https://leanpub.com/tr4w">Reading The Rails 4 Way</a></li>
</ul>
<p>Michael Hartl has an excellent book and set of videos on building a Rails application. Michael takes the reader through creating a Twitter clone. You learn how to build a Rails application using TDD, custom authentication model and user profile images are also part of his tutorial. I enjoyed it from start to finish, if you want to <a href="/posts/an-introduction-to-rails-ruby-on-rails-tutorial/">read my review here it is</a>.</p>
<p><a href="/posts/railscasts-another-awesome-resource-for-rails-and-ruby/">Railscasts</a> are a collection of videos created by Ryan Bates. They are usually between 5 - 12 minutes and cover various topics in Rails. Many of the videos cover older versions of Rails, but there is a ton of videos that are as relevant as always. I have been watching a <a href="/posts/railscasts-another-awesome-resource-for-rails-and-ruby/">Railscasts</a> every morning on my ferry ride to work.</p>
<p>I wrote a series of posts on the <a href="/posts/a-journey-on-sending-emails-action-mailer/">ActionMailer</a>, <a href="/posts/a-journey-on-sending-emails-the-mail-gem/">Mail</a>, <a href="/posts/a-journey-on-sending-emails-the-pony-gem/">Pony</a> and the <a href="/posts/sending-emails-using-ruby-with-nothing-more-than-the-core-library-and-a-csv/">Standard Library’s</a> email functionality. It was a great way to go through the different gems and compare them. In the end, I wrote down my suggestions and all the code I used for these posts are public Gists. If you would like to read my thoughts here are the posts for <a href="/posts/a-journey-on-sending-emails-action-mailer/">ActionMailer</a>, <a href="/posts/a-journey-on-sending-emails-the-mail-gem/">Mail</a>, <a href="/posts/a-journey-on-sending-emails-the-pony-gem/">Pony</a> and <a href="/posts/sending-emails-using-ruby-with-nothing-more-than-the-core-library-and-a-csv/">Standard Library</a>.</p>
<p><a href="/posts/codeschool-they-finally-have-my-money/">Code School</a>, I subscribed to <a href="/posts/codeschool-they-finally-have-my-money/">Code School</a> after watching an episode of Feature Focus, and I can honestly say the price paid for a subscription is money well spent. So far I have finished Try Ruby, Ruby Bits, Ruby Bits Part 2, Rails for Zombies, Rails for Zombies 2, Try Git and am 76% finished with Rails 4: Zombie Outlaws. Gregg Pollack and his team have done an excellent job, and the way they teach is just plain awesome.</p>
<p>I also started converting a <a href="/posts/database-migrations-converting-dbscriptomate-to-ruby/">C# database migration</a> tool over to Ruby and while its been great I haven’t done as well in posting on how the migration process is going. The coming weeks I hope to restart those posts to share with everyone how I rewrote an SQL Server migration tool.</p>
<p>When I first started learning Rails, I bought The Rails 4 Way. The Rails 4 Way is not a book for a beginner; you should get some Rails under your belt before reading it. Only after completing the Rails Tutorial and the <a href="/posts/codeschool-they-finally-have-my-money/">Code School</a> courses do I grasp what is going on in The Rails 4 Way. The book is a gem though and is definitely worth buying.</p>
<p>Finally, I would also like to mention the <a href="http://guides.rubyonrails.org/">Rails Guides</a>, the <a href="http://guides.rubyonrails.org/">Rails Guides</a> are excellent! There have been various times when I just needed some examples that I jumped into the <a href="http://guides.rubyonrails.org/">Rails Guides</a> and found much more info than I needed. The documents are maintained by a passionate bunch of people, and I hope they continue doing an excellent job. If you are learning Rails bookmark the <a href="http://guides.rubyonrails.org/">Rails Guides</a> website and reference it all the time.</p>
<p>In closing I am happy with my progress, I am feeling more and more confident in my Ruby and Rails ability as each day passes and most of all I am enjoying the learning experience.</p>
<hr />
Damn Good Documents Make the Difference2014-08-18T00:00:00+00:00http://deonheyns.com/posts/damn-good-documents-make-the-difference<p>When I started out coding as my Senior Developer was my buddy. We worked in a hybrid environment; we would write C# and UniVerse Basic code. I wasn’t that comfortable with Basic and would rather just code away in C#. So when I was assigned to him I thought to myself this was going to be so awesome, I can ask him anything and he will just have the answer. Well, I was mistaken every time I asked him something his first reply would be “Have you read the documentation?”, my response for the first two weeks would always be “No, I haven’t.” So with my tail between my legs I would go and read the UniVerse documentation.</p>
<p>Him sending me back to read the documentation was the best thing ever to happen to me. When you go a read API documentation, you tend to grasp it much better than just being told to do things in a certain way. What ends up happening is a lot of tests, or throwaway code is written so that you can learn this API. That means that you have a reference and some working code the next time you run into a similar problem.</p>
<p>Now in the C# world I don’t think many would argue that the MSDN documentation is just plain bad. The guys over at Microsoft could have done a much better job then they have. In my opinion, the one Microsoft property that has good documentation is the ASP.NET site. They have decent and recent tutorials, and the articles are well written. What is missing is try API documentation, the no frills kind of stuff, the type of documentation where it’s straight to the point with concise examples.</p>
<p>Over the last few weeks I have found myself reading a lot of <a href="https://www.ruby-lang.org/en/">Ruby</a> code, I believe this is a good way to learn. However, just recently did I discover what great documentation is provide to [Rails][rails] developers on the <a href="http://guides.rubyonrails.org/">Rails Guides</a> website. I love reading their documentation; that is the sort of documentation that every library should have.</p>
<p>Need to get started with [Rails][rails]? That’s there and is well-written need help with Migrations? How about Views? Having issues Mail or your Controllers? Or do you just need some pointers on testing? Well, look no further than the <a href="http://guides.rubyonrails.org/">Rails Guides</a> website.</p>
<p>What impresses me is how well these documents are written, clearly a lot of time and effort has gone into making this world class. Not only is <a href="https://www.ruby-lang.org/en/">Ruby</a> a great language to use, not only does [Rails][rails] make web development a pleasure but now they even make working with their documentation as easy as pie. I can now see why <a href="https://www.ruby-lang.org/en/">Ruby</a> and [Rails][rails] are so popular, there is a lot of efforts that goes into making this a wonderful eco-system and it is no wonder that all Rubyists seem like the happy hippy trippy kind of people.</p>
<p>So do yourself a favor have a look at the <a href="http://guides.rubyonrails.org/">Rails Guides</a> website that is what documentation truly is.</p>
<hr />
Open Bermuda - Open Source Software and the Community2014-08-17T00:00:00+00:00http://deonheyns.com/posts/open-bermuda-open-source-software-and-the-community<p>I live in Bermuda; it’s a small island off the east of the USA. There are about 65 000 people on this island. A lot of Reinsurance companies are here as well as a fair share of Hedge Funds. International business accounts for a large portion of the economy here in Bermuda.</p>
<p>Bermuda being as small as it is can obviously not supply all the skills needed by these large companies. Thus, there is a fair amount of expatriate workers here which is good and bad for the country. The good is that these people come here to live and work, this means money is moving through the country. The bad part is that there is much in the way of knowledge sharing and up-skilling of local Bermudians.</p>
<p>Whilst living in South Africa, I loved going to user groups and hack-a-tons. These events were a great place to meet like-minded and not so like-minded individuals, but most of all they were a great place to learn about writing good software. There was no prerequisite to attend these events, any person interested in software could come along and learn.</p>
<p>Bermuda doesn’t have these sorts of events; there was a .NET user group but I haven’t heard or seen them advertising any events. The .NET user group was also more about people just speaking about a topic, and there would be no hands on labs. This is what Bermuda needs; there needs to be a Meetup where people can come and learn.</p>
<p>Last week I found my way into a discussion of software enthusiasts to start just such a group. A place where we could share knowledge and mentor young people that have a passion for software.</p>
<p>We agreed that Python would be the best option (though I will be throwing in Ruby here and there :)), especially since to get from zero to coding with Python is very quick. The first meeting will happen on the 20th of August 2014 at the Chamber of Commerce in Hamilton.</p>
<p>There is a <a href="https://groups.google.com/forum/#!forum/open-bermuda">Google group</a> setup so if you are interested in how this all plays out please join the discussion</p>
<hr />
Code School - They Finally have my Money2014-08-16T00:00:00+00:00http://deonheyns.com/posts/codeschool-they-finally-have-my-money<p>So I discovered <a href="https://www.codeschool.com/">Code School</a> a few years back, maybe around 2010 or 2011. At that time, I was much more into Microsoft technologies than <a href="https://www.ruby-lang.org/en/">Ruby</a> or anything open source. Since I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> I try and find as many good sources of information that will help me to learn <a href="https://www.ruby-lang.org/en/">Ruby</a> but will also help me to grow as a developer. Being in technology means trying to keep up to date with the latest frameworks, languages and techniques that come out, this is pretty difficult when you have a full-time job and a family.</p>
<p>I watched the first <a href="https://www.codeschool.com/screencasts/basecamp-search">Feature Focus</a> with <a href="http://twitter.com/greggpollack">Gregg Pollack</a> and <a href="http://twitter.com/caike">Carlos Souza</a> last week, at that point I made a decision that I would sign up for Code School and at $29 a month it won’t make a massive dent in my pocket ;). Feature Focus walks you through implementing features that are in Basecamp, upon completion of these features Gregg and Carlos present their solution to David Heinemeier Hansson, the Founder and CTO of Basecamp (and creator of <a href="https://www.ruby-lang.org/en/">Ruby</a> on <a href="http://rubyonrails.org/">Rails</a>), who provides feedback on their feature implementation. I find it pretty invaluable as someone very new to <a href="https://www.ruby-lang.org/en/">Ruby</a> and <a href="http://rubyonrails.org/">Rails</a> to see how these veterans implement solutions and how David the father of <a href="http://rubyonrails.org/">Rails</a> gives some great feedback that can be used in any language and web framework.</p>
<p>The way Code School is structured down paths to learning specific skills. They have paths covering <a href="https://www.ruby-lang.org/en/">Ruby</a>, HTML/CSS, JavaScript and iOS. Each path has at last six courses covering various topics, and they include exercises. If I have learned anything in my time as a developer, there is no better way to learn then by doing. There is even an electives path that has a bunch of courses dealing with the R programming language, Git, Chrome DevTools and various other topics.</p>
<p>At the moment, I am obviously most interested in the <a href="https://www.ruby-lang.org/en/">Ruby</a> track which deals with the <a href="https://www.ruby-lang.org/en/">Ruby</a> language, <a href="http://rubyonrails.org/">Rails</a> and Testing. My experience, thus far, just wow! The presenters are all knowledgeable, and they get the point across very well. I also appreciate that after each course there is an outro video with more info on what the next steps are.</p>
<p>If <a href="https://www.ruby-lang.org/en/">Ruby</a> is a programming language created for developer happiness then, Code School is a learning site created for utter learner joy!</p>
<p>Gregg and team keep up the good work!</p>
<hr />
Haiku Friday - 55 Days of Writing2014-08-15T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-55-days-of-writing<p>##It started 55 posts ago
<img src="http://deonheyns.com/images/55.png" alt="It started 55 posts ago" /></p>
<p>##The journey to better writing
<img src="http://deonheyns.com/images/will_shake.jpg" alt="I could always watch one of these" /></p>
<p>##One blogpost a day
<img src="http://deonheyns.com/images/bermudian_sunrise.jpg" alt="One blogpost a day" /></p>
<p>This week I wrote my 55th blogpost which is also 55 days of continuous writing. Here is to the next 55!</p>
<hr />
Transformation Thursday - More on Modules from a Pro2014-08-14T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-more-on-modules-from-a-pro<p>I was going to write some more about Modules today but after reading Practicing Ruby for some inspiration I don’t think I could do better than Gregory Brown done with his series of posts.</p>
<p><a href="https://practicingruby.com/articles/uses-for-modules-1">Uses for Modules, Part 1</a></p>
<p><a href="https://practicingruby.com/articles/uses-for-modules-2">Uses for Modules, Part 2</a></p>
<p><a href="https://practicingruby.com/articles/uses-for-modules-3">Uses for Modules, Part 3</a></p>
<p><a href="https://practicingruby.com/articles/uses-for-modules-3a">Addendum to Uses For Modules, Part 3</a></p>
<p><a href="https://practicingruby.com/articles/uses-for-modules-4">Uses for Modules, Part 4</a></p>
<p>There are some extremely smart people in the Ruby Community and Gregory Brown is one of them.</p>
<ul>
<li>Part 1 deals with the use of modules as namespaces for your libraries and applications.</li>
<li>Part 2 is about mixins as an alternative to multiple inheritance to augment class definitions.</li>
<li>In part 3 you will see how modules can be used as namespaced function bags, and as singleton objects.</li>
<li>In the addendum to part 3 you learn about the subtle differences between “extend self”, “def self.method”, and “module_function”.</li>
<li>Part 4 ends the series by exploring the use of mixins for customizing individual objects.</li>
</ul>
<p>You might say this is a cop-out on my side by these articles on Modules do much more justice to an advance topic made easy by a knowledgeable author.</p>
<p>So happy reading I enjoyed the articles and I hope you do too.</p>
<hr />
Database Migrations Converting DbScriptomate to Ruby Run SQL Scripts Take 12014-08-13T00:00:00+00:00http://deonheyns.com/posts/database-migrations-converting-dbscriptomate-to-ruby-run-sql-scripts-take-1<p>So I had a quick spike tonight to find a way to run SQL scripts against SQL Server. I found <a href="https://github.com/rails-sqlserver/tiny_tds">TinyTDS</a> that piggybacks off of <a href="http://www.freetds.org/">FreeTDS</a>. <a href="https://github.com/rails-sqlserver/tiny_tds">TinyTDS</a> - A modern, simple and fast <a href="http://www.freetds.org/">FreeTDS</a> library for Ruby using DB-Library. <a href="http://www.freetds.org/">FreeTDS</a> is a set of libraries for Unix and Linux that allows your programs to talk natively to Microsoft SQL Server and Sybase databases.</p>
<p>To get started, you are going to need to install <a href="http://www.freetds.org/">FreeTDS</a>. <a href="http://www.freetds.org/">FreeTDS</a> is available through <a href="http://brew.sh/">homebrew</a>, if you don’t have <a href="http://brew.sh/">homebrew</a> installed you can head over to the <a href="http://brew.sh/">homebrew</a> site and follow the steps to get it installed. If you have <a href="http://brew.sh/">homebrew</a> installed then just type in:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>brew install freetds
</code></pre></div></div>
<p>Next you will want to install the <a href="https://github.com/rails-sqlserver/tiny_tds">TinyTDS</a> gem, all you need to type is:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem install tiny_tds
</code></pre></div></div>
<p>All setup lets write some code to send some SQL commands to our SQL Server.</p>
<script src="https://gist.github.com/DeonHeyns/ac7d5967dcda9fd86e1f.js"> </script>
<p>Just one require pulling tiny_tds, we can then new up an instance of the Client class. The Client class accepts a few options, here is the full list of options:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>:username - The database server user.
:password - The user password.
:dataserver - The name for your data server as defined in freetds.conf. Raw hostname or hostname:port will work here too.
:host - Used if :dataserver blank. Can be an host name or IP.
:port - Defaults to 1433. Only used if :host is used.
:database - The default database to use.
:appname - Short string seen in SQL Servers process/activity window.
:tds_version - TDS version. Defaults to "71" (7.1) and is not recommended to change!
:login_timeout - Seconds to wait for login. Default to 60 seconds.
:timeout - Seconds to wait for a response to a SQL command. Default 5 seconds.
:encoding - Any valid iconv value like CP1251 or ISO-8859-1. Default UTF-8.
:azure - Pass true to signal that you are connecting to azure.
</code></pre></div></div>
<p>For our use we are only going to need:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>:username
:password
:host
:database
</code></pre></div></div>
<p>Setting these options are just enough for our spike. Next we call the execute method on the client instance passing in the SQL statement to be executed. The execute method returns a Result object that will allow us to loop over and readout all the rows from the result of our SQL expression.</p>
<p>Finally, to be safe we call close on the connection just to be safe and ensure we cleanup after ourselves.</p>
<p>With this code, I was able to execute CRUD operations and create a stored procedure. This means that <a href="https://github.com/rails-sqlserver/tiny_tds">TinyTDS</a> looks like it can handle my requirements. The next step is to start writing tests that we can test that our SQL statements are correctly executed when using DbScriptomate.</p>
<p>Tomorrow we take a break to talk about Modules again, but this weekend we will dive back into this code and run some migration scripts against our DB!</p>
<hr />
Word Scoring - Solution and Thoughts About Optimization2014-08-12T00:00:00+00:00http://deonheyns.com/posts/word-scoring-solution-and-thoughts-about-optimization<p>I was watching a video today where they had a theoretical word scoring game. The scoring rules were as follows</p>
<ul>
<li>2 for a,i,e,o</li>
<li>3 for f</li>
<li>5 for t</li>
<li>6 for j</li>
<li>12 for x</li>
</ul>
<p>I wrote this code to do the scoring:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">module</span> <span class="nn">Scorer</span>
<span class="k">class</span> <span class="nc">WordScore</span>
<span class="k">def</span> <span class="nf">initialize</span>
<span class="vi">@letters</span> <span class="o">=</span> <span class="no">Hash</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="vi">@letters</span> <span class="o">=</span> <span class="vi">@letters</span><span class="p">.</span><span class="nf">merge</span><span class="p">(</span>
<span class="p">{</span> <span class="s1">'f'</span> <span class="o">=&gt;</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">'j'</span> <span class="o">=&gt;</span> <span class="mi">6</span><span class="p">,</span>
<span class="s1">'x'</span> <span class="o">=&gt;</span> <span class="mi">12</span><span class="p">,</span> <span class="s1">'a'</span> <span class="o">=&gt;</span> <span class="mi">2</span><span class="p">,</span>
<span class="s1">'i'</span> <span class="o">=&gt;</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'e'</span> <span class="o">=&gt;</span> <span class="mi">2</span><span class="p">,</span>
<span class="s1">'o'</span> <span class="o">=&gt;</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'t'</span> <span class="o">=&gt;</span> <span class="mi">5</span><span class="p">})</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">word_score</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>
<span class="n">word</span><span class="p">.</span><span class="nf">downcase!</span>
<span class="n">score</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">word</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="s1">''</span><span class="p">).</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">letter</span><span class="o">|</span>
<span class="n">score</span> <span class="o">+=</span> <span class="vi">@letters</span><span class="p">[</span><span class="n">letter</span><span class="p">]</span>
<span class="k">end</span>
<span class="n">score</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="n">counter</span> <span class="o">=</span> <span class="no">Scorer</span><span class="o">::</span><span class="no">WordScore</span><span class="p">.</span><span class="nf">new</span>
<span class="nb">puts</span> <span class="s2">"The score is </span><span class="si">#{</span><span class="n">counter</span><span class="p">.</span><span class="nf">word_score</span><span class="p">(</span><span class="s1">'XRay Machine'</span><span class="p">)</span><span class="si">}</span><span class="s2">"</span>
<span class="nb">puts</span> <span class="s2">"The score is </span><span class="si">#{</span><span class="n">counter</span><span class="p">.</span><span class="nf">word_score</span><span class="p">(</span><span class="s1">'Jabbt'</span><span class="p">)</span><span class="si">}</span><span class="s2">"</span></code></pre></figure>
<p>My biggest gripe at the moment is this line of code:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="vi">@letters</span> <span class="o">=</span> <span class="no">Hash</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="vi">@letters</span> <span class="o">=</span> <span class="vi">@letters</span><span class="p">.</span><span class="nf">merge</span><span class="p">(</span>
<span class="p">{</span> <span class="s1">'f'</span> <span class="o">=&gt;</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">'j'</span> <span class="o">=&gt;</span> <span class="mi">6</span><span class="p">,</span>
<span class="s1">'x'</span> <span class="o">=&gt;</span> <span class="mi">12</span><span class="p">,</span> <span class="s1">'a'</span> <span class="o">=&gt;</span> <span class="mi">2</span><span class="p">,</span>
<span class="s1">'i'</span> <span class="o">=&gt;</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'e'</span> <span class="o">=&gt;</span> <span class="mi">2</span><span class="p">,</span>
<span class="s1">'o'</span> <span class="o">=&gt;</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">'t'</span> <span class="o">=&gt;</span> <span class="mi">5</span><span class="p">})</span></code></pre></figure>
<p>There must be a simpler and better way to do this. I am going to dig into the different Ruby collections over the next few days to fix that line of code. Thereafter I would like to jump into the loop I do in these lines:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">word</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="s1">''</span><span class="p">).</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">letter</span><span class="o">|</span>
<span class="n">score</span> <span class="o">+=</span> <span class="vi">@letters</span><span class="p">[</span><span class="n">letter</span><span class="p">]</span>
<span class="k">end</span></code></pre></figure>
<p>Again there must be a more Ruby way of doing this kind of thing, not only that but there must be a more efficient way of calculating the score.</p>
<p>As an aside I didn’t get a chance to write more code in converting <a href="/posts/database-migrations-converting-dbscriptomate-to-ruby/">DbScriptomate</a> to Ruby so that is left for tomorrow.</p>
<hr />
Database Migrations Converting DbScriptomate to Ruby - Command Line Arguments2014-08-11T00:00:00+00:00http://deonheyns.com/posts/database-migrations-converting-dbscriptomate-to-ruby-command-line-arguments<p>The first part of our conversion of DbScriptomate to Ruby is to accept command line arguments. Any useful console based application accepts parameters passed to it via the command line. Accepting command line parameters will also make it possible to run our application via scripts as part of a build system.</p>
<p>Based on the command the application will need different parameters; the commands necessary in DbScriptomate are:</p>
<ul>
<li>setupdb - this will setup the database for initial use</li>
<li>migrate - will run all the migration files</li>
<li>generate - will generate a new migration script</li>
</ul>
<p>To setup the database for the first time and to run the migration scripts some parameters necessary are:</p>
<ul>
<li>Host - the name or IP address of the machine where our SQL database is running</li>
<li>Database Name - the database against which we need to run the scripts</li>
<li>Username - the user that has the correct permissions to run these scripts</li>
<li>Password - the password of the user</li>
<li>Port - the port used to connect to the database</li>
</ul>
<p>To generate a new migration script DbScriptomate will need:</p>
<ul>
<li>Type - is this a DDL or DML script (Stored Procedure or CRUD)</li>
<li>Your initials - the initials of the current user</li>
<li>Description - a description or summary of what this migration script will do.</li>
</ul>
<p>We are at a good place to start. Before we do anything else, we need to setup our file structure. Create a new folder called dbscriptomate, within the folder create a bin, lib and test folder. A good place to start is testing that our application can indeed accept command line arguments. Create a file within the test folder called commands_tests.rb.</p>
<p>Now we can write our first test. The first requirement is that the application accept the commands setupdb, migrate and generate. We are going to need these commands to invoke the different operations, and a class called Command seems like a good choice to me. We can start off by mixing our tests and implementation in one code file and refactor as we go along. Let’s write a test.</p>
<p>We need to make sure we can parse the command so lets start there. To call DbScriptomate we are going to pass the arguments as follow:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>generate -h 127.0.0.1 -n test -u admin -p password -o 14332 -t ddl -i dh -d description
</code></pre></div></div>
<p>The first argument is the actual command, the rest of the arguments are for connecting to the database. Here is the first test to ensure we cover the generate, migrate and setupdb commands.</p>
<script src="https://gist.github.com/DeonHeyns/52267d796457be3698ad.js"> </script>
<p>The code to make this pass is quite simple:</p>
<script src="https://gist.github.com/DeonHeyns/07a327a845738d9623ad.js"> </script>
<p>We now have just enough code to make this pass. We can now parse the rest of the arguments. Here comes the awesome bit, Ruby has the OptionParser class. The OptionParser allows for easy parsing of command line arguments. We are going to use OptionParser to get the other parameters that can be passed in, here are our tests to prove that the parsing works:</p>
<script src="https://gist.github.com/DeonHeyns/23e7897497ea35c3949a.js"> </script>
<p>We will modify the initialize method to setup our OptionParser:</p>
<script src="https://gist.github.com/DeonHeyns/4c6cc6e14b18384e6f1e.js"> </script>
<p>Let’s step through this code to detail what is going on. We have a variable called parameters which will expose our parsed command line arguments. We pull out the operation and store that for later use. The OptionParser class takes in a block that will firstly define a few details that will be displayed when calling help, there after we have a few more blocks that set our parameters Hash. Finally, we call the parse! (pronounced parse bang) method that will execute all the blocks from above thereby parsing the arguments passed in.</p>
<p>This is just enough code to get us going on this journey and it is also enough code to show how awesome Ruby is. Tomorrow we are going to write some code that uses the operation and parameters.</p>
<hr />
Database Migrations Converting DbScriptomate to Ruby2014-08-10T00:00:00+00:00http://deonheyns.com/posts/database-migrations-converting-dbscriptomate-to-ruby<p>I am working with a buddy of mine on a database migration tool. It is like Active Record Migrations but customized to our specific needs. The project is called <a href="https://github.com/InivitSystems/DbScriptomate">DbScriptomate</a> and if you are developing code in the Microsoft world using SQL Server then check it out now! I will wait while you go check it, seriously I am patient.</p>
<p><a href="https://github.com/InivitSystems/DbScriptomate">DbScriptomate</a> works by accepting command line arguments. It can setup your database server for first-time use, create your migration script or run the migration scripts to get your database in sync with everyone on your team. We are looking to simplify the way we parse the command line arguments. We could cleanup our code somewhat and take a bunch of complexity out at the same time if we do this correctly. In the .NET world there is no built-in way to do the parsing of the arguments, you need to do all the argument parsing by hand. There are some good tools to get this job done though and by just googling “command line parse .net c#” you will get a few libraries.</p>
<p>So whilst going through the <a href="https://github.com/InivitSystems/DbScriptomate">DbScriptomate</a> today I had a brilliant idea. In my attempt to <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learn</a> <a href="https://www.ruby-lang.org/en/">Ruby</a>, I tend to take C# code and convert that to <a href="https://www.ruby-lang.org/en/">Ruby</a>. Thus far I have done small things like <a href="/posts/string-substitution-and-fixing-the-send-email-with-csv-code/">csv</a> parsing, <a href="/posts/sending-emails-using-ruby-with-nothing-more-than-the-core-library-and-a-csv/">email</a> and <a href="/posts/csharp-to-ruby-how-to-base64-encode/">base64</a> encoding. I thought what a great idea if I could take <a href="https://github.com/InivitSystems/DbScriptomate">DbScriptomate</a> and convert it to <a href="https://www.ruby-lang.org/en/">Ruby</a>, I know the code-base and the requirements so this should be a fun ride.</p>
<p>So here is my plan to do this conversion:</p>
<ol>
<li>Command line parsing</li>
<li>Support to run scripts against a database</li>
<li>Initial setup of Journaling table</li>
<li>Generate a migration script whether it is DDL or DML</li>
<li>Ensure scripts are only run once</li>
<li>Run the scripts against the database</li>
</ol>
<p>I am sure I will be adding some more steps here because I am sure <a href="http://subvertingcomplexity.com/">Jacques</a> will remind me of something I missed. I am going to start in the order above and work my way through. This could take me a couple weeks depending on workload, but I am looking forward to this series of posts. All the code will be available on <a href="https://github.com/DeonHeyns/DbScriptomate.rb">GitHub</a> in this <a href="https://github.com/DeonHeyns/DbScriptomate.rb">repository</a> for everyone to follow along with.</p>
<p>Just before anyone jumps up and says “hey you already have this in x, y and z library” let me say this is just for me to learn. I have no intention of making this a gem and I will not be using this in production. Active Record Migrations is great for this sort of thing so stick with that.</p>
<p>Hope you are as excited as I am! Also checkout <a href="http://subvertingcomplexity.com/">Jacques’</a> blog he has some good posts on continuous delivery and other useful tidbits that will make you a better developer.</p>
<hr />
Railscasts - Another awesome resource for Rails and Ruby2014-08-09T00:00:00+00:00http://deonheyns.com/posts/railscasts-another-awesome-resource-for-rails-and-ruby<p>I must have said it a hundred and one or tow times already, but I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> and having an absolute ball. Already my mind has been opened to a new way of thinking. I keep finding excellent sites like the <a href="/posts/practicing-ruby-some-awesome-lessons-for-all-programmers">Ruby Koans</a> and <a href="/posts/more-awesome-ruby-resources/">Confreaks</a>.</p>
<p>Tonight I want to share <a href="http://railscasts.com/">Railscasts</a>. RailsCasts are created and produced by <a href="https://twitter.com/rbates">Ryan Bates</a>, though Ryan has taken a break from producing new <a href="http://railscasts.com/">Railscasts</a> the ones that are there are real gems.</p>
<p>The videos are short and focus on one technique, so you aren’t confused by too many different parts; thus, you can quickly move on to applying it to your projects. The topics target toward the intermediate Rails developer, but so far as a beginner none have been overwhelming. The videos are easy to follow along with and if you want you can get the code from the <a href="http://railscasts.com/">Railscast</a> <a href="https://github.com/ryanb/railscasts-episodes">Github repo</a>.</p>
<p>I am watching a <a href="http://railscasts.com/">Railscast</a> each morning before I leave for work, you can call it my espresso for the day. They are something you should be aware of, and you should schedule a video if not every day at least once a week.</p>
<p>Oh and if you are wondering about new <a href="http://railscasts.com/">Railscasts</a> being produced <a href="https://twitter.com/rbates">Ryan</a> has this posted up on the <a href="http://railscasts.com/">Railscast</a> website:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>RailsCasts Status
You have probably noticed there has been a lack of new episodes lately.
I have found it increasingly difficult to produce content,
and I'm not entirely sure why. The best way I can describe it is that
I feel paralyzed under the pressures of work.
I have decided to take a Summer break to help me come up with a solution.
I will return on September 2 with new content.
All Pro subscriptions have been automatically extended by
two months (no need to press a button this time).
New subscribers during this time will be charged the initial $9
and then have their subscription extended through September.
Thank you for your patience during this time! :)
--Ryan
</code></pre></div></div>
<p>Let’s hope <a href="https://twitter.com/rbates">Ryan</a> feels refreshed soon as I am sure there is some <a href="http://rubyonrails.org/">Rails 4.x</a> goodness he can share.</p>
<hr />
Haiku Friday - Need to send emails in Ruby?2014-08-08T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-need-to-send-email-ruby<p>##Send Email in Ruby
<img src="http://deonheyns.com/images/send_emails.jpeg" alt="email" /></p>
<p>##There is much choice in Ruby Gems
<img src="http://deonheyns.com/images/ruby.png" alt="ruby" /></p>
<p>##The answer right here now!
<a href="/">
<img src="http://deonheyns.com/images/dh.png" alt="dh" />
</a>
—</p>
Transformation Thursday - C# to Ruby, Referencing and using other libraries2014-08-07T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-moving-from-csharp-to-ruby-referencing-and-using-other-libraries<p>I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> and thought it would be useful to other .NET developers who are coming to <a href="https://www.ruby-lang.org/en/">Ruby</a> to understand the differences.</p>
<p>I’ve covered:</p>
<ul>
<li><a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-namespace-in-ruby">Namespaces</a></li>
<li><a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-class-in-ruby">Classes</a></li>
<li><a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-method-in-ruby/">Methods</a></li>
<li><a href="/posts/transformation-thursday-csharp-to-ruby-how-do-properties-work-in-ruby/">Properties</a></li>
</ul>
<p>Today I wanted to take a look at using and referencing other libraries. In the .NET world we are fortunate enough to have one of the best if not the best IDEs in Visual Studio. In Visual Studio it is a matter of right-click, add Reference and you select the assembly you wish. Once you have added the reference you want the next step is to add a using statement to the class file where you will be using the referenced assembly’s functionality.</p>
<p>Here is a class declaration with a few using statements needed to send an email in C#.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>using System.Net;
using System.Net.Mail;
namespace Foo {
class Bar {
void SendEmail(string to, string from, string subject, string body) {
// implementation
}
}
}
</code></pre></div></div>
<p>So how do you go ahead and do the same in <a href="https://www.ruby-lang.org/en/">Ruby</a>? Let me introduce you to the require and load keyword. Require, and Load are global functions defined in Object but are used like language keywords.</p>
<p>There is a small difference between require and load. The load keyword includes the Ruby source file every time it is called. Require which is more commonly used will only include the source file once and then caches it.</p>
<p>If you were paying attention you would have noticed I mentioned source files, <a href="https://www.ruby-lang.org/en/">Ruby</a> is a scripting language it does not compile down to a dynamic link library or similar. When using require or load there is no need to include the ‘.rb’ file extension.</p>
<p>The exact syntax to require or load a <a href="https://www.ruby-lang.org/en/">Ruby</a> source file is</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>require 'net/smtp'
module Foo
class Bar
def send_email(to, from, subject, body)
# implementation
end
end
</code></pre></div></div>
<p>or</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>load 'net/smtp'
module Foo
class Bar
def send_email(to, from, subject, body)
# implementation
end
end
</code></pre></div></div>
<p>Pretty simple and straightforward, that is the theme in <a href="https://www.ruby-lang.org/en/">Ruby</a>. We have covered the basic structure of a <a href="https://www.ruby-lang.org/en/">Ruby</a> program. In the next Transformation Thursday post, I would like to circle back and look at <a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-namespace-in-ruby">Modules</a> once more.</p>
<hr />
An introduction to Rails - Ruby on Rails Tutorial2014-08-06T00:00:00+00:00http://deonheyns.com/posts/an-introduction-to-rails-ruby-on-rails-tutorial<p>About a month ago I wrote about Michael Hartl’s Ruby on Rails Tutorial. I finished the tutorial over the weekend and thought I would share my thoughts.</p>
<p>Here is the table of contents:</p>
<ul>
<li>Chapter 1 From zero to deploy</li>
<li>Chapter 2 A demo app</li>
<li>Chapter 3 Mostly static pages</li>
<li>Chapter 4 Rails-flavored Ruby</li>
<li>Chapter 5 Filling in the layout</li>
<li>Chapter 6 Modeling users</li>
<li>Chapter 7 Sign up</li>
<li>Chapter 8 Sign in, sign out</li>
<li>Chapter 9 Updating, showing, and deleting users</li>
<li>Chapter 10 User microposts</li>
<li>Chapter 11 Following users</li>
</ul>
<p>Michael starts off by getting a simple application created and deployed to Heroku within the first chapter. Deploying a web application this fast was simply awesome, quickly you realize that the deployment story is going to be a sweet one. You are no longer worried coming from platform X that the barrier to entry is going to be enormous.</p>
<p>Chapter 2 has you creating a new demo Rails application using the scaffolder however Michael quickly tells the reader that relying on the scaffolder will not teach you Rails and to become a good Rails developer you will need to learn how a Rails application is put together.</p>
<p>In Chapter 3, you start building out a Twitter clone (if you didn’t know Twitter previously was a Rails backed DB application). You start building out a few pages that will not have any / much dynamic content.</p>
<p>Chapter 4 is all about Rails and Ruby; it has been said before that the barrier to entry to Rails is very low. Rails is much more a DSL over Ruby, and it’s very easy to pick up what is going on. That being said to be a truly great Rails developer you will need to know Ruby fairly well.</p>
<p>Chapter 5 is a lot of fun working with SASS you learn how to put together and edit stylesheets in a more programmatic way. I have looked at LESS and SASS before but never done much with it until this tutorial. Let it be known that with this tutorial does not make you a Rails guru, it’s a great introduction but you won’t come away from this tutorial ready to build the next Facebook or Twitter.</p>
<p>Chapter 6 starts getting into Models and ActiveRecord you really start writing a ton of tests at this point. Michael has a very straightforward approach to testing that I like it makes a lot of sense, and the tools available in Ruby makes this a very pleasant experience.</p>
<p>Chapter 7 has you build the sign up process and show the user’s profile that leads nicely into Chapter 8.</p>
<p>Chapter 8 is all about creating a custom security system for the Twitter clone. Some might say just use Devise or another authentication and authorization library. As the author states, most sites require quite a bit of customization when it comes to security systems. Modifying third-party libraries sometimes entail more work than rolling your own. Also, its good to know how these sort of systems work and what better way to find out than rolling your own.</p>
<p>Chapter 9 gets you going with CRUD operations on the user; this is done via Rails design to match REST verbs. If you don’t know what REST is, this is the chapter where some of the mysteries are unveiled.</p>
<p>Chapter 10 finally gets you to the real part of the clone, the mircoposts. The reader is introduced to associations in this chapter and a few partials are built too. After this chapter the application comes to life, you get to login to the application and post various messages like you do on Twitter.</p>
<p>Chapter 11 the final chapter, the last chapter covers following and unfollowing users. It is by far the most intense chapter and deals with associative tables and the use of raw SQL to do some of the magic.</p>
<p>Throughout the whole tutorial you are writing tests TDD style, you are working with views, partial views, stylesheets, GIT is used heavily through the tutorial and during most chapters you are doing database migrations.</p>
<p>This tutorial was awesome. I had a great time working through it; however, my time with the Ruby on Rails Tutorial is not over yet. I still have the videos to watch and would like to complete the exercises provided in the last chapter.</p>
<p>All in all a great tutorial and I highly recommend it.</p>
<hr />
A journey on sending emails - the end2014-08-05T00:00:00+00:00http://deonheyns.com/posts/a-journey-on-sending-emails-the-conclusion<p>So the last few days I posted on how to send emails in <a href="https://www.ruby-lang.org/en/">Ruby</a>, it was all started by this <a href="/posts/csharp-to-ruby-how-to-send-an-email-message/">post</a>. Here are the posts on using <a href="/posts/a-journey-on-sending-emails-action-mailer/">ActionMailer</a>, <a href="/posts/a-journey-on-sending-emails-the-mail-gem/">Mail</a> and <a href="/posts/a-journey-on-sending-emails-the-pony-gem/">Pony</a>.
These are the main players together with the Standard Library in sending emails. Based on these posts here are my opinions of the Pros and Cons of using each library.</p>
<p>##<a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a>
###Pros</p>
<ul>
<li>Widely used, its part of <a href="http://rubyonrails.org/">Rails</a></li>
<li>Well tested</li>
<li>Under active development</li>
<li>You get to use templates with little to no boilerplate code</li>
<li>Can send and process incoming emails</li>
</ul>
<p>###Cons</p>
<ul>
<li>It has quite a few dependencies</li>
<li>Need to override where the infrastructure looks for templates</li>
<li>Not able to send an email in a single line (elegantly)</li>
</ul>
<p>##<a href="https://github.com/mikel/mail">Mail</a>
###Pros</p>
<ul>
<li>Used by both <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> and <a href="https://github.com/benprew/pony">Pony</a> internally so even more widely used then <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a></li>
<li>Gives you full control on where your templates live</li>
<li>Can send and process incoming emails</li>
<li>Well tested</li>
<li>Under active development</li>
<li>Lightweight has no dependencies on external gems</li>
<li>From the same person that created TMail</li>
</ul>
<p>###Cons</p>
<ul>
<li>You need to write the code to process templates</li>
<li>Not able to send an email in a single line (elegantly)</li>
</ul>
<p>##<a href="https://github.com/benprew/pony">Pony</a>
###Pros</p>
<ul>
<li>Built on top of <a href="https://github.com/mikel/mail">Mail</a></li>
<li>You can send an email in a single line</li>
<li>Well tested</li>
<li>Gives you full control on where your templates live</li>
<li>Under active development</li>
</ul>
<p>###Cons</p>
<ul>
<li>Can only be used to send emails</li>
<li>Has a few dependencies on external gems</li>
<li>Not as widely used</li>
<li>You need to write the code to process templates</li>
</ul>
<p>So with the Pros and Cons out of the way who is the winner?</p>
<p>Honestly they all are, you see each library has its place and caters to different use cases.</p>
<p>If you are building a <a href="http://rubyonrails.org/">Rails</a> application then there is no reason to go and reinvent the wheel, <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> is great and everybody is using it;
it’s built upon <a href="https://github.com/mikel/mail">Mail</a>, so it has a fantastic foundation.</p>
<p>If you need email sending and processing then by all means use <a href="https://github.com/mikel/mail">Mail</a> in your <a href="https://www.ruby-lang.org/en/">Ruby</a> applications. <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> and <a href="https://github.com/benprew/pony">Pony</a> are both built on top of this library and it’s great at what it was built to do.</p>
<p>If all you need is email sending then <a href="https://github.com/benprew/pony">Pony</a> is awesome, you get all the power of <a href="https://github.com/mikel/mail">Mail</a> and with minimal work you are out the gate.</p>
<p>That leaves one option though, what about the Standard Library? The Standard Library is great, it too has minimal setup, and my first choice is always to stick to whatever is in the Standard Library, however, the gems available give you a great abstraction and will allow you to switch between different mail protocols with minimal work.</p>
<p>It has been quite a learning experience to write about these different libraries I encourage you to do the same.</p>
<hr />
A journey on sending emails - the Pony gem2014-08-04T00:00:00+00:00http://deonheyns.com/posts/a-journey-on-sending-emails-the-pony-gem<p>This is my third post on sending emails in <a href="https://www.ruby-lang.org/en/">Ruby</a>; you can find the first <a href="/posts/a-journey-on-sending-emails-action-mailer/">here</a> and second <a href="/posts/a-journey-on-sending-emails-the-mail-gem/">here</a>. Today we are going to use <a href="https://github.com/benprew/pony">Pony</a> to send out our email. <a href="https://github.com/benprew/pony">Pony</a>, claims to be the express way to send emails in <a href="https://www.ruby-lang.org/en/">Ruby</a>, it was created to give Rubyist the same feel as PHP’s mail function that sends an email in a single command.</p>
<p><a href="https://github.com/benprew/pony">Pony</a> uses /usr/sbin/sendmail to send mail if it is available; otherwise it will fall-back to SMTP. You can specify from the get go that <a href="https://github.com/benprew/pony">Pony</a> uses one or the other. Just as <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> does <a href="https://github.com/benprew/pony">Pony</a> uses the <a href="https://github.com/mikel/mail">Mail</a> gem to do the heavy lifting and thus your emails are sent through a tried and tested library used by the majority of the <a href="https://www.ruby-lang.org/en/">Ruby</a> world.</p>
<p>Since <a href="https://github.com/benprew/pony">Pony</a> uses <a href="https://github.com/mikel/mail">Mail</a> internally, you will see a lot of similarities between it, <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> and <a href="https://github.com/mikel/mail">Mail</a>. <a href="https://github.com/benprew/pony">Pony</a> is exclusively used to send an email if you would like to process incoming emails you are better off using <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> or better yet plain old <a href="https://github.com/mikel/mail">Mail</a>.</p>
<p>So getting down to business, we will want to create a new <a href="https://www.ruby-lang.org/en/">Ruby</a> file for our <a href="https://github.com/benprew/pony">Pony</a> mailer class. I am going to go ahead and call it using-pony-mail.rb. The first thing you need to do is install the <a href="https://github.com/benprew/pony">Pony</a> gem using</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>install gem pony
</code></pre></div></div>
<p>Next you need to add two requires to your using-pony-mail.rb file, a require to ERB and a require to <a href="https://github.com/benprew/pony">Pony</a>. Your file should look like this:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>require 'erb'
require 'pony'
</code></pre></div></div>
<p>We will be using ERB to process our email template which means we can use variables in our email template that will be replaced at runtime.</p>
<p>The next step is to define our Mailer class; the Mailer class will receive an options Hash in the initialize method that will be passed off to <a href="https://github.com/benprew/pony">Pony</a>. Inside our initialize method, we will set the Pony.options.</p>
<script src="https://gist.github.com/DeonHeyns/1ca9bd0d6d25a7b3c526.js"> </script>
<p>The Mailer class will need a method that will be called to send our email as with our previous examples we will call this method awesome_email which will accept a Hash called details that will hold everything that is necessary for our email.</p>
<script src="https://gist.github.com/DeonHeyns/092c168d59d1f05118e0.js"> </script>
<p>In the awesome_email method, we set the context that will be passed off to ERB. The binding class captures the execution context; this is crucial as without the context your variables will not be visible to ERB when generating the email body for your message.</p>
<p>We are now ready to set our options Hash; this Hash is passed into the Mailer constructor and sets certain properties within <a href="https://github.com/benprew/pony">Pony</a>. Unlike before we, have two new keys in our Hash. The first is the :via_options symbol which contains the SMTP details and then another new symbol :via which states which mechanism to use in sending our emails, since we are using Gmail we are passing in SMTP.</p>
<script src="https://gist.github.com/DeonHeyns/4d368dd392044c81cb65.js"> </script>
<p>Great we can now create the Mailer object that will be used to send out the email passing in the options Hash that <a href="https://github.com/benprew/pony">Pony</a> will need. We can also create our details Hash with all the necessary information to set the from and to addresses, the subject line of the email and the path to the email template that ERB will use when sending out an email. Lastly, we can call the awesome_email method on the Mailer object that we created and pass in the details Hash. Here is the full code listing:</p>
<script src="https://gist.github.com/DeonHeyns/c2dde0d8a21cf73a4771.js"> </script>
<p>Thus, far I believe this has been the least amount of code written between the <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> and Mailer implementations. <a href="https://github.com/benprew/pony">Pony</a> has quite a nice API, which is straightforward. <a href="https://github.com/benprew/pony">Pony</a> is pretty awesome if all you need to do is send an email; it uses <a href="https://github.com/mikel/mail">Mail</a> internally which is used by <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> and well tested and is actively being developed. If all you are going to do is send an email then <a href="https://github.com/benprew/pony">Pony</a> should be your first choice, if you need to process incoming emails I would say use <a href="https://github.com/mikel/mail">Mail</a> and if you are building a <a href="http://rubyonrails.org/">Rails</a> application just stick to <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a>.</p>
<p>I am starting to see a trend here; both <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> and <a href="https://github.com/benprew/pony">Pony</a> are built on top of <a href="https://github.com/mikel/mail">Mail</a> it looks to me that <a href="https://github.com/mikel/mail">Mail</a> is the defacto API used to send emails in modern <a href="https://www.ruby-lang.org/en/">Ruby</a> libraries.</p>
<hr />
A journey on sending emails - the Mail gem2014-08-03T00:00:00+00:00http://deonheyns.com/posts/a-journey-on-sending-emails-the-mail-gem<p><a href="/posts/2014-08-02-a-journey-on-sending-emails-action-mailer">Yesterday I took a look at sending emails</a> using <a href="https://rubygems.org/gems/actionmailer">ActionMailer</a>. Today I want to go through the same exercise, but this time we will use the <a href="https://github.com/mikel/mail">Mail gem</a>. <a href="https://rubygems.org/gems/actionmailer">ActionMailer</a> uses Mail <a href="https://github.com/rails/rails/blob/master/actionmailer/lib/action_mailer/base.rb">internally</a>; you will see some similarity in the code we wrote in <a href="/posts/2014-08-02-a-journey-on-sending-emails-action-mailer">yesterday’s</a> post.</p>
<p>Some history on the <a href="https://github.com/mikel/mail">Mail</a> library. <a href="https://github.com/mikel/mail">Mail</a> was designed to handle email generation, parsing and sending in the <a href="/posts/the-ruby-way-what-does-it-mean">Ruby way</a>. <a href="https://github.com/mikel/mail">Mail</a> is from the same author that gave us TMail. Based on his experience on TMail he built <a href="https://github.com/mikel/mail">Mail</a> from the ground up to make generating, sending and parsing emails a no-brainer. <a href="https://github.com/mikel/mail">Mail</a> has been designed to work with <a href="https://www.ruby-lang.org/en/">Ruby</a> &gt; 1.9; it works with <a href="https://www.ruby-lang.org/en/">Ruby</a> 1.8.x but it’s not as easy.</p>
<p>Awesome thanks for the history lesson Deon, let’s get down to business. Go ahead and create a new <a href="https://www.ruby-lang.org/en/">Ruby</a> file creatively called mailer2.rb, you will need two requires. In no particular order, you will need to require ‘mail’ and ‘erb’. Why do you need <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/erb/rdoc/ERB.html">ERB</a> you might ask, we are going to use a template for our email body and <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/erb/rdoc/ERB.html">ERB</a> is going to do the heavy lifting for us. If you didn’t know you can use <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/erb/rdoc/ERB.html">ERB</a> for your templating needs, how awesome is that? Also at this point we can also declare our class called Mailer but before we do that let’s just install the <a href="https://github.com/mikel/mail">Mail</a> gem:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem install mail
</code></pre></div></div>
<p>Just like the code for <a href="https://rubygems.org/gems/actionmailer">ActionMailer</a> there are certain properties we must set in order to send emails successfully. This time around we are going to set these properties in our initialize method, with the addition of this code our file should look like so:</p>
<script src="https://gist.github.com/DeonHeyns/1b27b11cd5b9297a1f53.js"> </script>
<p>Next thing we are going to do is write the code that will set the variables needed in our template, create our <a href="https://github.com/mikel/mail">Mail</a> object, set the necessary properties on our mail object and do the sending, sounds like quite a bit of work but it isn’t really.</p>
<script src="https://gist.github.com/DeonHeyns/4ed7e3aff28bf6b86b84.js"> </script>
<p>The awesome_email method is expecting a details hash. The details Hash will contain the addresses for the to and from addresses, the subject and the path to the template for the body of our email.</p>
<p>The code is very straightforward until this line:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>b = binding
</code></pre></div></div>
<p>Binding captures the execution context at this point of the code, and this is crucial as without the context your variables will not be visible to <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/erb/rdoc/ERB.html">ERB</a> when generating the email body for your message. In hindsight, a better name for the b variable might have been ‘context’ but it’s not such a big issue.</p>
<p>The next interesting part of this method is how we create the body of our email. Here we are using <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/erb/rdoc/ERB.html">ERB</a>, which works by building a chunk of Ruby code that will output the completed template when run. The whole body of our email is magically created within a single line of code:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>mail.body = ERB.new(File.read(template_path)).result(b)
</code></pre></div></div>
<p>The template for our email looks as follows:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Hello this email has been sent to &lt;%= @to %&gt; from &lt;%= @from %&gt;
</code></pre></div></div>
<p>The last line of code might look very familiar, it is the same code we used in the <a href="https://rubygems.org/gems/actionmailer">ActionMailer</a> implementation to do the actually sending of our code.</p>
<p>We are now in a good place to send an actual email. We are going to create a Hash with the necessary setting for <a href="https://github.com/mikel/mail">Mail</a>, what you will notice again is how similar it is compared to the code for <a href="https://rubygems.org/gems/actionmailer">ActionMailer</a>, and again that is because internally <a href="https://rubygems.org/gems/actionmailer">ActionMailer</a> uses <a href="https://github.com/mikel/mail">Mail</a>.</p>
<script src="https://gist.github.com/DeonHeyns/25e444b0ac59c48d94a2.js"> </script>
<p>With our options in place, we can now create a new Mailer object and pass in our options. Next we require the details Hash that will be necessary for the email, in our case we have an email template in the mailer folder called ‘awesome_email.html.erb’ you could have called this template whatever you wanted <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/erb/rdoc/ERB.html">ERB</a> would not have cared. We can now call the ‘awesome_email’ method passing in our details Hash to send our email. Here is the full code listing:</p>
<script src="https://gist.github.com/DeonHeyns/8112b6fc55f7d7806bfa.js"> </script>
<p>Compared to the <a href="/posts/csharp-to-ruby-how-to-send-an-email-message/">first attempt</a> at sending email this implementation hides us from the complexity of sending an email when using the <a href="http://ruby-doc.org/stdlib-2.0/libdoc/net/smtp/rdoc/Net/SMTP.html">Standard Library</a>. If we compare the <a href="https://rubygems.org/gems/actionmailer">ActionMailer</a> implementation to this, it seems we are in a better place with this code. We are abstracted away from the <a href="http://ruby-doc.org/stdlib-2.0/libdoc/net/smtp/rdoc/Net/SMTP.html">Standard Library</a> so no matter if we need to send an email via SMTP or POP3 we just flip a flag and change a few settings. This implementation doesn’t pull all of the dependencies that <a href="https://rubygems.org/gems/actionmailer">ActionMailer</a> requires, and we still get templating via <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/erb/rdoc/ERB.html">ERB</a> (also noting we could have used <a href="http://ruby-doc.org/stdlib-2.1.2/libdoc/erb/rdoc/ERB.html">ERB</a> in <a href="/posts/string-substitution-and-fixing-the-send-email-with-csv-code/">previous</a> <a href="/posts/string-substitution-and-fixing-the-send-email-with-csv-code/">implementations</a> without an issue).</p>
<p><a href="https://rubygems.org/gems/actionmailer">ActionMailer</a> is perfect for your <a href="http://rubyonrails.org/">Rails</a> applications, and you should use <a href="https://github.com/mikel/mail">Mail</a> in your other Ruby applications. There are still a few more mail sending gems to go so right now I am not going to declare a winner.</p>
<hr />
A journey on sending emails - ActionMailer2014-08-02T00:00:00+00:00http://deonheyns.com/posts/a-journey-on-sending-emails-action-mailer<p>Today I was playing around with <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> and using it outside of <a href="http://rubyonrails.org/">Rails</a> to send emails. I have previously written about <a href="/posts/string-substitution-and-fixing-the-send-email-with-csv-code/">sending emails</a> in <a href="https://www.ruby-lang.org/en/">Ruby</a>. What I discovered on the <a href="https://www.ruby-toolbox.com/">Ruby toolbox</a> is that there are quite a few different ways to send emails using <a href="https://www.ruby-lang.org/en/">Ruby</a>. So I would like to take you through using <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> outside of a <a href="http://rubyonrails.org/">Rails</a> application.</p>
<p><a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> allows you to send an email from your application using a mailer model and views. What this means you can pass a model with different properties to a regular ERB view and based on that model you will have different information you can use in the email you intend to send. The great thing about using views as your email templates is that you get to use the full power of the ERB processor, and you can put in proper separation between your application code and email templates.</p>
<p>As with most things in <a href="http://rubyonrails.org/">Rails</a> there are certain conventions that <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> expects but thankfully they are over-ridable. Enough with the talking give me the skinny.</p>
<p>First thing is to make sure you have the <a href="https://rubygems.org/gems/actionmailer">ActionMailer gem</a>; you can install the <a href="https://rubygems.org/gems/actionmailer">ActionMailer gem</a> with</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>gem install actionmailer
</code></pre></div></div>
<p>alternatively you can create a gemfile and include the <a href="https://rubygems.org/gems/actionmailer">ActionMailer gem</a> in there.</p>
<p>Great you now have the required gem installed, and you are ready to start writing some code.</p>
<p>At the top of your .rb file, you will need a directive to require the <a href="https://rubygems.org/gems/actionmailer">ActionMailer gem</a>.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>require 'action_mailer'
</code></pre></div></div>
<p>Depending on the method of delivery you will want to set the delivery_method. I am using Gmail as my mail server with SMTP, so I need to pass along that configuration to <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a>. Here is what your file should look like this thus far:</p>
<script src="https://gist.github.com/DeonHeyns/1e7cecd33e08c2bbd3f9.js"> </script>
<p>With this boilerplate code in place, we can start writing our mail sending code.</p>
<p>You need to define a class that inherits from ActionMailer::Base. Inheriting from the Base class will give us the ‘deliver’ method that is necessary to do the actual sending.</p>
<p>Here is how our code with the configuration and class definition:</p>
<script src="https://gist.github.com/DeonHeyns/0c8ca6eae844e5156ddd.js"> </script>
<p>Now we are ready to write a method that will do the work of creating an email and setting variables that we need in our email template.</p>
<p>In our method, we want to set variables that are going to be used in the template as well as in the sending of the email. In our example, we need the ‘to’ and ‘from’ addresses as well as the ‘subject’ of the email. To pass in these different parameters we are going to use a Hash, creatively called details. First here is our method declaration:</p>
<script src="https://gist.github.com/DeonHeyns/80f9aaa7c32793065e0a.js"> </script>
<p>Once we add the awesome_email method to our Mailer class and set the Hash with the details, our code should look like this:</p>
<script src="https://gist.github.com/DeonHeyns/6b5790f4bea3f92ee195.js"> </script>
<p>Here comes the one thing that might trip you up. <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> uses convention over configuration; this is the <a href="http://rubyonrails.org/">Rails</a> way. Convention over configuration allows things to work automagically but in our case we do not have the whole <a href="http://rubyonrails.org/">Rails</a> shebang, so we need to override some of that convention to allow our mailing system to work.</p>
<p>We need to let <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> know where to look for our views. That can be done by setting the ‘view_paths’ property to the same path as our mailer script.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ActionMailer::Base.view_paths= File.dirname(__FILE__)
</code></pre></div></div>
<table>
<tbody>
<tr>
<td>When <a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> now scans for the email templates it will follow the convention mailer_script_path/class_name/method_name.(html</td>
<td>text).erb. If we look at this convention, we see that we can have HTML and plain text versions of our email template.</td>
</tr>
</tbody>
</table>
<p>Awesome we are now ready to create our email template. Go ahead and create a directory called mailer. Inside of mailer you will need to create a file awesome_email.html.erb since we are only going to send the HTML version of our template, so there is no need to create a plain text version.</p>
<p>Using ERB means we can pass along variables to our email templates. This is extremely handy as email templates are exactly that, templates that need certain information supplied to work correctly. To reference a variable inside of your template, you will need a class level instance variable, so a variable whose name starts with the ‘@’ symbol. If we look at the awesome_email method, we see we have two such variables ‘@to’ and ‘@from’. Inside the awesome_email.html.erb email template you need to add the following to make use of these variables:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Hello this email has been sent to &lt;%= @to %&gt; from &lt;%= @from %&gt;
</code></pre></div></div>
<p>Great the majority of our email sending code is complete as well as a template. At this point, we are ready to send an email. Here is the simple code you will need to send an email using your Mailer class:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>email = Mailer.awesome_email( details )
email.deliver
</code></pre></div></div>
<p>Here is the full code listing:</p>
<script src="https://gist.github.com/DeonHeyns/405cb532d623e65b605e.js"> </script>
<p><a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> is by far the most-used email gem in Ruby, from what I see the majority of that is from <a href="http://rubyonrails.org/">Rails</a> applications, it has a simple API, and it is quite straightforward to getting it working in any application.</p>
<p><a href="https://github.com/rails/rails/tree/master/actionmailer">ActionMailer</a> comes with a lot of dependencies, so it’s not as clean as <a href="/posts/csharp-to-ruby-how-to-send-an-email-message/">sending</a> an email using the <a href="http://ruby-doc.org/stdlib-2.0/libdoc/net/smtp/rdoc/Net/SMTP.html">Standard Library</a> but it is well-tested and widely used, so you are definitely in good company.</p>
<hr />
Haiku Friday - Save the drama for yo mama2014-08-01T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-save-the-drama-for-yo-mama<p>##In the pursuit of drama
<img src="http://deonheyns.com/images/drama_alert.png" alt="OMFG Drama ahead" /></p>
<p>##You may try ABC, HBO or Showtime
<img src="http://deonheyns.com/images/drama_channels.png" alt="I could always watch one of these" /></p>
<p>##Instead Google Node JS
<img src="http://deonheyns.com/images/congrats_for_the_drama.jpg" alt="Or just google Node JS" /></p>
<p>This weeks Haiku was inspired by <a href="http://hueniverse.com/2014/07/30/open-source-dickishness/">Open Source Dickishness</a> and <a href="https://medium.com/code-adventures/40b8bcb8e5af">StrongLoop &amp; Express</a>.</p>
<hr />
Transformation Thursday - C# to Ruby, How do properties work in Ruby2014-07-31T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-csharp-to-ruby-how-do-properties-work-in-ruby<p>I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> and thought it would be useful to other .NET developers who are coming to <a href="https://www.ruby-lang.org/en/">Ruby</a> to understand the differences.</p>
<p>I’ve covered <a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-namespace-in-ruby">Namespaces</a>, <a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-class-in-ruby">Classes</a> and <a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-method-in-ruby/">Methods</a> previously and would like to follow that up with Properties.</p>
<p>Here is some new code to work with this week.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="kp">public</span> <span class="k">class</span> <span class="nc">Employee</span>
<span class="p">{</span>
<span class="sr">//</span> <span class="k">class</span> <span class="n">level</span> <span class="n">variable</span> <span class="n">shared</span> <span class="n">by</span> <span class="n">all</span> <span class="n">classes</span>
<span class="kp">public</span> <span class="n">static</span> <span class="n">int</span> <span class="no">NumberOfEmployees</span><span class="p">;</span>
<span class="kp">private</span> <span class="n">static</span> <span class="n">int</span> <span class="n">counter</span><span class="p">;</span>
<span class="sr">//</span> <span class="n">instance</span> <span class="n">level</span> <span class="kp">private</span> <span class="n">variable</span>
<span class="kp">private</span> <span class="n">string</span> <span class="nb">name</span><span class="p">;</span>
<span class="sr">//</span> <span class="no">A</span> <span class="n">read</span><span class="o">-</span><span class="n">write</span> <span class="n">instance</span> <span class="ss">property:
</span><span class="kp">public</span> <span class="n">string</span> <span class="no">Name</span>
<span class="p">{</span>
<span class="n">get</span> <span class="p">{</span> <span class="k">return</span> <span class="nb">name</span><span class="p">;</span> <span class="p">}</span>
<span class="n">set</span> <span class="p">{</span> <span class="nb">name</span> <span class="o">=</span> <span class="n">value</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
<span class="sr">//</span> <span class="no">A</span> <span class="n">read</span><span class="o">-</span><span class="n">only</span> <span class="n">static</span> <span class="ss">property:
</span><span class="kp">public</span> <span class="n">static</span> <span class="n">int</span> <span class="no">Counter</span>
<span class="p">{</span>
<span class="n">get</span> <span class="p">{</span> <span class="k">return</span> <span class="n">counter</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
<span class="sr">//</span> <span class="no">A</span> <span class="no">Constructor</span><span class="p">:</span>
<span class="kp">public</span> <span class="no">Employee</span><span class="p">()</span>
<span class="p">{</span>
<span class="sr">//</span> <span class="no">Calculate</span> <span class="n">the</span> <span class="n">employee</span><span class="err">'</span><span class="n">s</span> <span class="ss">number:
</span><span class="n">counter</span> <span class="o">=</span> <span class="o">++</span><span class="n">counter</span> <span class="o">+</span> <span class="no">NumberOfEmployees</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p>First let’s get familiar with what properties are. Properties are a combined aspects of both fields and methods. When writing to a property you will use the following syntax:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">someClass</span><span class="o">.</span><span class="no">Property</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span></code></pre></figure>
<p>When reading you will use this syntax:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">var</span> <span class="n">variable</span> <span class="o">=</span> <span class="n">someClass</span><span class="o">.</span><span class="no">Property</span><span class="p">;</span></code></pre></figure>
<p>Now when implementing a class that has properties, your property is one of two code blocks, it is either a get accessor and or a set accessor. When you read or get a property, the get accessor code block is executed and likewise when you write or set the property the set accessor code block is executed. Should you have a property that only has the get accessor it is considered read-only. When a property only has a set accessor it is a write-only property.</p>
<p>Properties are declared in the class by specifying the access modifiers (as we discussed in the post on <a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-method-in-ruby/">methods</a>), the type (i.e. whether it is an int, string, bool) and the name of the property.</p>
<p>Properties are a great way to run some logic before gaining access to the field. So taking our code from above here we can see the different parts.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>private string name;
// access modfier: public
// type: string
// property name: Name
public string Name
{
get { return name; }
set { name = value; }
}
</code></pre></div></div>
<p>In this example we see that Name is backed by a private field variable name, it has been made public and returns a string. At this point, I think we have covered enough on the C# side of properties</p>
<p>Let’s see the same implementation in <a href="https://www.ruby-lang.org/en/">Ruby</a>.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Employee</span>
<span class="c1"># class level field shared by all variables
</span>
<span class="vc">@@number_of_employees</span> <span class="o">=</span> <span class="mi">0</span>
<span class="c1"># gives us access to the class level property using Employee.number_of_employees
</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">number_of_employees</span>
<span class="vc">@@number_of_employees</span>
<span class="k">end</span>
<span class="c1"># A read instance property:
</span>
<span class="k">def</span> <span class="nf">name</span>
<span class="vi">@name</span>
<span class="k">end</span>
<span class="c1"># A write instance property:
</span>
<span class="k">def</span> <span class="nf">name</span><span class="o">=</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
<span class="vi">@name</span> <span class="o">=</span> <span class="nb">name</span>
<span class="k">end</span>
<span class="c1"># A Constructor:
</span>
<span class="k">def</span> <span class="nf">initialize</span>
<span class="vc">@@number_of_employees</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>Unlike C#, there is no static keyword in <a href="https://www.ruby-lang.org/en/">Ruby</a>, and all properties are public unless specified otherwise. A double “@” denotes that this is a class level variable and thus will be shared amongst different instances. Class level variables / properties are exposed by:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="vc">@@number_of_employees</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">number_of_employees</span>
<span class="vc">@@number_of_employees</span>
<span class="k">end</span></code></pre></figure>
<p>A single “@” specifies that this is an instance level variable and thus each class object created will have its version of this property. <a href="https://www.ruby-lang.org/en/">Ruby</a> does not have a get and set keywords so instead you create you’re get and set accessors by defining the using the following syntax:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># Get accessor
</span>
<span class="k">def</span> <span class="nf">name</span>
<span class="vi">@name</span>
<span class="k">end</span>
<span class="c1"># Set accessor
</span>
<span class="k">def</span> <span class="nf">name</span><span class="o">=</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
<span class="vi">@name</span> <span class="o">=</span> <span class="nb">name</span>
<span class="k">end</span></code></pre></figure>
<p>If you need to access any of these properties in your class, you will include the “@” sign in-front of the variable name</p>
<p>Just like C# has automatic backed variables using:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="kp">public</span> <span class="n">string</span> <span class="no">Name</span> <span class="p">{</span> <span class="n">get</span><span class="p">;</span> <span class="n">set</span> <span class="p">}</span></code></pre></figure>
<p><a href="https://www.ruby-lang.org/en/">Ruby</a> too has this ability:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># Read, Write accessor
</span>
<span class="nb">attr_accessor</span> <span class="ss">:name</span>
<span class="c1"># Readonly accessor
</span>
<span class="nb">attr_reader</span> <span class="ss">:name</span>
<span class="c1"># Write accessor
</span>
<span class="nb">attr_writer</span> <span class="ss">:name</span></code></pre></figure>
<p>Both languages have interesting approaches to this problem. As you can see coming from the .NET world this is very different to what we are accustomed to but not rocket science either. I hope this was helpful to you.</p>
<hr />
Handy chruby commands2014-07-30T00:00:00+00:00http://deonheyns.com/posts/handy-chruby-commands<p>I previously wrote about some handy <a href="/posts/handy-rvm-commands">rvm</a> commands, thereafter I found out that there are a few more <a href="https://www.ruby-lang.org/en/">Ruby</a> managers. It seems to me that the main Ruby version managers are <a href="/posts/handy-rvm-commands">rvm</a>, <a href="https://github.com/postmodern/chruby">chruby</a> and rbenv.</p>
<p>So let’s have a look at <a href="https://github.com/postmodern/chruby">chruby</a>. Firstly if you have homebrew installed you can easily get <a href="https://github.com/postmodern/chruby">chruby</a> up and running. All you need to do is</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>brew install chruby
</code></pre></div></div>
<p>What versions of <a href="https://www.ruby-lang.org/en/">Ruby</a> do you have?</p>
<pre><code class="language-chruby">$ chruby
</code></pre>
<p>This returns a list similar to</p>
<pre><code class="language-chruby">$ chruby
* ruby-2.0.0-p195
ruby-2.0.0-p481
ruby-2.1.0
</code></pre>
<p>Need to select a particular Ruby to use?</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ chruby 1.9.3
</code></pre></div></div>
<p>This will switch to ruby-1.9.3.</p>
<p>When needing to work or manage gemsets it seems that [bundler] is the answer. <a href="https://github.com/postmodern/chruby">Chruby</a> seems to be very focused on managing rubies and is not a full featured toolbelt like <a href="/posts/handy-rvm-commands">rvm</a>.</p>
<p>I intend to follow up tomorrow with another post on <a href="https://github.com/postmodern/chruby">Chruby</a>, as I believe there is more to it than what I discovered tonight.</p>
<hr />
Grammarly for people like me who suck at grammar and stuff2014-07-29T00:00:00+00:00http://deonheyns.com/posts/grammarly-for-people-like-me-who-suck-at-grammar-and-stuff<p>My spelling and grammar are atrocious, not by a little bit by a long bit! I always thought that my grammar was okay. I knew it wasn’t stellar but never realized how bad it was. I should have paid more attention in school, but I was too busy with sport and other what seemed at that time important things.</p>
<p>Since I started writing a blog post a day my poor grammar has become more evident. I have a coach helping me on my <a href="/posts/rails-here-is-my-plan-to-learn-ruby">journey</a>. Bless him for articulating in such a pleasant manner that my grammar is poor. If the roles were reversed I am not sure if I would be as polite as he has been about my writing.</p>
<p>So how does a person go about fixing or working on their spelling and grammar? Well, I think it’s the same as coding. The more you read and write the better you get. There are also obviously much quicker fixes like word processors that will quickly give you feedback about your spelling and grammar.</p>
<p>I found <a href="http://www.grammarly.com/">Grammarly</a>, which is one such tool. It will give you quick feedback on grammatical errors and spelling mistakes. The <a href="http://www.grammarly.com/">Grammarly</a> website states</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Grammarly is an automated proofreader and your personal grammar coach
Correct up to 10 times more mistakes than popular word processors.
</code></pre></div></div>
<p>I signed up for <a href="http://www.grammarly.com/">Grammarly</a> and have slowing been making my way through my previous posts and fixing them up. So far it has been very good and whilst I don’t always score a 100% rating, the grammar in my blog posts seem to be much better.</p>
<p>I do want to make it clear that this is just a crutch; I should be reading and writing a lot more so that I can stop making these grammatical errors that would shock a fifth grader.</p>
<p>So I know this was a non-technical post but I am sure if you use something like <a href="http://www.grammarly.com/">Grammarly</a> or similar your readers will be much happier reading what you have to say, so here is to getting a “Well that was profound” reaction instead of a WTF after each sentence.</p>
<hr />
And now I present Initials Avatar2014-07-28T00:00:00+00:00http://deonheyns.com/posts/and-now-i-present-initials-avatar<p>I double as the <a href="https://www.atlassian.com/software/jira">JIRA</a> administrator at my job. So today a user ask me to switch their profile avatar back to the colored background with their initial. I searched for any clue on how to revert avatars in <a href="https://www.atlassian.com/software/jira">JIRA</a> and found nothing. Then I had the bright idea that I would just change it at the database level, yeah that wasn’t a great idea either. At this point, I thought I would just tell them it is not possible but that would make me look like a chump.</p>
<p>So I went about looking for a solution on <a href="https://github.com/">GitHub</a> and found something that almost got me there. With a bit of code here and there, some pixie dust for good measure I came up with a very crude implementation of <a href="http://initials-avatar.com/">Initials Avatar</a>. I was quickly able to generate a new “initials avatar” for the users and just distributed them to those who preferred the “initial avatars” over regular ones.</p>
<p>I was pretty happy, but I remembered how difficult it was to find a website that done this for me. So being a good web citizen I decided to create a <a href="http://initials-avatar.com/">website</a> where anyone can come and create their own “initials avatar.”</p>
<p>So how do you do this? Well, pretty simply you head off to <a href="http://initials-avatar.com/">http://initials-avatar.com/</a> enter your initials, pick a background and, foreground color then some magic happens, and you get a new shiny avatar with your initials.</p>
<p>Here are some not so important things that might or might not interest you</p>
<ul>
<li>The initials are restricted to three characters. Any character after the first three initials will be ignored</li>
<li>You can enter the hex code for your color omitting the hash symbol ‘#’ aka pound aka number</li>
<li>If you’d like you can use RGB values. An example would be RGB(195,79,76)</li>
<li>Then normal word colors can be entered, pink, blue, orange, etc.</li>
<li><del>To save the avatar right-click on it select the option “Save Image As.”</del> Click the Save! button</li>
</ul>
<p>With creating this website, I truly stood on the shoulders of giants. I built the site using <a href="http://getbootstrap.com/">Bootstrap</a>, <a href="http://www.sinatrarb.com/">Sinatra</a>, <a href="https://dashboard.heroku.com/apps">Heroku</a> and source from <a href="https://github.com/loopj/initials-avatar">GitHub</a>.</p>
<p>It was a great learning experience and what was even more awesome was using some of the <a href="https://www.ruby-lang.org/en/">Ruby</a> I have recently learned to get things up and running.</p>
<p>Enjoy and go ahead and create yourself a new avatar <a href="http://initials-avatar.com/">http://initials-avatar.com/</a>.</p>
<hr />
What is Acceptance Criteria?2014-07-27T00:00:00+00:00http://deonheyns.com/posts/what-is-acceptance-criteria<p>I had a business user ask me</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>"what is acceptance criteria?".
</code></pre></div></div>
<p>I scoffed and thought</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Acceptance criteria? That is so easy how can an English speaking person not know
what acceptance criteria is or means?
</code></pre></div></div>
<p>I started to reply to the user’s email, I then realized that explaining the meaning of acceptance criteria (in the agile world) wasn’t as easy as I thought.</p>
<p>So I started to break down the meaning. I asked myself what is acceptance criteria in lay-man’s terms?</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Acceptance Criteria is a list of items that must be delivered in order to mark a feature as complete.
</code></pre></div></div>
<p>Okay seems simple enough, and this is what I sent back to the user. They replied to my explanation with</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>"Thank you for the explanation but it is still not clear to me what Acceptance Criteria is. Could you give me more information."
</code></pre></div></div>
<p>So how can I explain this to a 5-year-old without coming across as being condescending? How can I make this as simple as possible. So I tried again?</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>When you asked for this new feature, in your mind it had to have the functionality that you wanted
The developer that will implement your new feature needs to get the big picture of what you want.
As the developer implements, your feature, they are going to tick items off that will make up the feature you want.
In other words, the developer needs to know what your requirements are in order to give you what you want.
A picture is worth a thousand words so any working examples or screen-shots or mocks will be valuable
</code></pre></div></div>
<p>I went even further and used an example I found.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>As a conference attendee, I want to be able to register on-line, so I can register quickly and cut down on paperwork
</code></pre></div></div>
<p>The acceptance criteria for this story would include</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1. A user cannot submit a form without completing all the mandatory fields
2. Information from the form is stored in the registrations database
3. Protection against Spam is working
4. Payment can be made via credit card
5. An acknowledgment email is sent to the user after submitting the form.
</code></pre></div></div>
<p>I thought long and hard about what is acceptance criteria and my different replies. The following questions popped up in my mind while doing this.</p>
<ul>
<li>Why is it so difficult for us to communicate to users what we really need from them?</li>
<li>Why don’t we have a glossary that each member of the team can maintain and distribute around to keep everyone on the same page.</li>
<li>Why do we keep making life so difficult for ourselves and our users?</li>
<li>Why do we keep giving explanations like:</li>
</ul>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Acceptance Criteria are a set of statements, each with a clear pass / fail result, that specify both functional
(e.g., minimal marketable functionality) and non-functional (e.g., minimal quality)
requirements applicable at the current stage of project integration. These requirements represent "conditions of satisfaction."
There is no partial acceptance: either a criterion is met or it is not.
</code></pre></div></div>
<p>instead of keeping it simple?</p>
<p>I don’t have the answers to these questions right now but surely if we as programmers / developers / engineers keep down this path we will further alienate the very people whose lives we are meant to make easier.</p>
<hr />
More awesome Ruby resources2014-07-26T00:00:00+00:00http://deonheyns.com/posts/more-awesome-ruby-resources<p>I must have said it a hundred times already, but I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> and having an absolute ball. Already my mind has been opened to a new way of thinking.</p>
<p>I will attend a <a href="https://www.ruby-lang.org/en/">Ruby</a> conference later this year either <a href="http://gogaruco.com/">Gogaruco</a> or <a href="http://madisonpl.us/ruby/">Madison + Ruby</a>, both look fantastic with some awesome speakers.</p>
<p>So tonight I was reading some <a href="/posts/practicing-ruby-some-awesome-lessons-for-all-programmers">Practicing Ruby</a> and somehow landed up on the <a href="http://rubyconf.org/">RubyConf</a> website. <a href="http://rubyconf.org/">RubyConf</a> looks like another excellent conference, and I am extremely jealous that the <a href="https://www.ruby-lang.org/en/">Ruby</a> community has so many cool conferences.</p>
<p>At present, I am all about getting in as much information as I can on <a href="https://www.ruby-lang.org/en/">Ruby</a> and <a href="http://rubyonrails.org/">Rails</a>. So while I was browsing around the <a href="http://rubyconf.org/">RubyConf</a> website I came across a link to <a href="http://confreaks.com/">Confreaks</a> website. I was totally blown away by all the great videos available on the <a href="http://confreaks.com/">Confreaks</a> website.</p>
<p>So starting Monday I plan to work one video in a day. I think I will start with the past videos of the conferences that interest me and then work my way around some of the others.</p>
<p>These are awesome videos and what is even better is they are all free! So have fun watching…</p>
<hr />
Haiku Friday - Ruby sometimes its black magic!2014-07-25T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-ruby-sometimes-its-black-magic<p>##Black Magic It Might Be
<img src="http://deonheyns.com/images/ruby.png" alt="ruby" /></p>
<p>##Deep Questions It Does Invoke
<img src="http://deonheyns.com/images/deep_questions.jpg" alt="Deep Questions" /></p>
<p>##Stop And Jump On The Ruby Tree
<img src="http://deonheyns.com/images/hammer_time.jpg" alt="Hammer Time" /></p>
<hr />
Transformation Thursday - C# to Ruby, What is the equivalent of a Method in Ruby2014-07-24T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-method-in-ruby<h3 id="why">Why?</h3>
<p>I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> and thought it would be useful to other .NET developers coming to <a href="https://www.ruby-lang.org/en/">Ruby</a> to understand the differences.</p>
<p>I covered <a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-namespace-in-ruby">Namespaces</a> and <a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-class-in-ruby">Classes</a> previously and would like to follow that up with the next part Methods.</p>
<p>Here is our FancyCalculator code again.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">namespace</span> <span class="no">Calculator</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="k">class</span> <span class="nc">FancyCalculator</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="no">FancyCalculator</span><span class="p">()</span>
<span class="p">{</span>
<span class="p">}</span>
<span class="kp">public</span> <span class="n">int</span> <span class="no">Add</span><span class="p">(</span><span class="n">int</span> <span class="n">lhs</span><span class="p">,</span> <span class="n">int</span> <span class="n">rhs</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p>In C# you need to declare your method as either private, public, protected, internal or protected internal. Depending on the access modifier you choose your method will be visible to only the class it is defined in or other classes. By not declaring an access modifier, you default your method to being private.</p>
<p>To jog our memory as to what the different access modifiers mean I have summarized them here.</p>
<p>Private: Access is limited to the containing type.
Public : Access is not restricted.
Protected: Access is limited to the containing class or types derived from the containing class.
Internal: Access is limited to the current assembly.
Protected Internal: Access is limited to the current assembly or types derived from the containing class.</p>
<p>Your method then needs to state whether it returns a value; reference type or void aka nothing aka nada aka niente aka niks. If we are returning anything from our method, we use the return keyword together with the result we want to return.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">return</span> <span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span></code></pre></figure>
<h3 id="how">How?</h3>
<p>Here is my <a href="https://www.ruby-lang.org/en/">Ruby</a> code again.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">module</span> <span class="nn">Calculator</span> <span class="c1"># a namespace
</span>
<span class="k">class</span> <span class="nc">FancyCalculator</span> <span class="c1"># a class
</span>
<span class="k">def</span> <span class="nf">initialize</span> <span class="c1"># a constructor
</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># a method in the class
</span>
<span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>The magic line is this</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># a method in the class
</span>
<span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="k">end</span></code></pre></figure>
<p>In <a href="https://www.ruby-lang.org/en/">Ruby</a>, all methods are public so everyone that has access to our class has access to its method. If we wanted to declare a method as private, we can do so by placing the private key once above the method we want private so let me illustrate this</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="kp">private</span>
<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># this is now private
</span>
<span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">subtract</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># this is now private too
</span>
<span class="n">lhs</span> <span class="o">-</span> <span class="n">rhs</span>
<span class="k">end</span>
<span class="c1"># anything below will be private too.</span></code></pre></figure>
<p>From what I gather it’s practice in the <a href="https://www.ruby-lang.org/en/">Ruby</a> community to indent the methods below the private keyword, this makes it much easier to see which methods are all private.</p>
<p>Another approach to making methods private is to pass the method symbols (we will cover symbols soon) to the private keyword as such:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># this is now private
</span>
<span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">subtract</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># this is now private too
</span>
<span class="n">lhs</span> <span class="o">-</span> <span class="n">rhs</span>
<span class="k">end</span>
<span class="ss">private: :add</span><span class="p">,</span> <span class="ss">:subtract</span></code></pre></figure>
<p>In <a href="https://www.ruby-lang.org/en/">Ruby</a>, you don’t need to use the return keyword explicitly in your method. In your method, the last line will always be returned. Also as you can see there is no indication as to what will be returned from the method.</p>
<h3 id="conclusion">Conclusion</h3>
<p>Major differences here are:</p>
<ul>
<li>No return type needs to be declared on the method</li>
<li>The last statement in a method will be returned. You can though at any time return something out of the method</li>
<li>Both languages have access modifiers but unlike C# <a href="https://www.ruby-lang.org/en/">Ruby</a> defaults to methods being public and any private methods must be explicitly declared.</li>
</ul>
<hr />
Practicing Ruby - some awesome lessons for all programmers2014-07-23T00:00:00+00:00http://deonheyns.com/posts/practicing-ruby-some-awesome-lessons-for-all-programmers<p>Tonight I am suffering with writer’s block. I am not sure of what to write about and the code that I wrote today was just plain useless (I tried to do some OCR using <a href="https://www.ruby-lang.org/en/">Ruby</a>).</p>
<p>I was <del>surfing</del> browsing the <del>interwebs</del> Internet trying to find some inspiration and came across <a href="https://practicingruby.com/">Practicing Ruby</a>. To quote directly from the <a href="https://practicingruby.com/">Practicing Ruby</a> website</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Practicing Ruby
Delightful lessons for dedicated programmers
Since 2010, Practicing Ruby has produced a total of 94 articles,
all of which were funded by our generous subscribers.
</code></pre></div></div>
<p>That is pretty impressive 94 articles which dive into topics such as Framework Design, Unobtrusive Ruby, Structural Design Patterns, Solid, How to practice and plenty more.</p>
<p>Some of the articles are written by the big names in <a href="https://www.ruby-lang.org/en/">Ruby</a> like Aaron Patterson and Avdi Grimm. I definitely see myself spending quite some time on this site going through these articles.</p>
<p>I did notice this bit of info above the massive “Subscribe to Practicing Ruby ($8/month)” button</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>If you enjoy these articles, please consider becoming a Practicing Ruby subscriber.
By doing so, you'll get immediate access to the 12 articles that we published between
April 2013 and March 2014 which have not been released to the public yet.
You'll also be supporting our work, as we continue on our mission to build a great
learning resource for all Ruby programmers.
</code></pre></div></div>
<p>I am pretty sure that if these articles are as great as they seem to be I will definitely be forking over some cash. I would suggest all developers regardless of their language of choice check out <a href="https://practicingruby.com/">Practicing Ruby</a> as the site clearly deals with Computer Programming topics that happen to be demonstrated in <a href="https://www.ruby-lang.org/en/">Ruby</a>.</p>
<hr />
String substitution and fixing the send email with csv code2014-07-22T00:00:00+00:00http://deonheyns.com/posts/string-substitution-and-fixing-the-send-email-with-csv-code<p>I am busy <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> each day I write some <a href="https://www.ruby-lang.org/en/">Ruby</a> no matter what. Well, except on Sundays I don’t write code on Sundays just because I need to <a href="/posts/on-the-importance-of-rest">rest</a> my brain. Yesterday I wrote this bit of <a href="/posts/sending-emails-using-ruby-with-nothing-more-than-the-core-library-and-a-csv">code</a> and to tell you the truth I didn’t like it one bit.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">require</span> <span class="s1">'net/smtp'</span>
<span class="n">addresses</span> <span class="o">=</span> <span class="no">File</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="s1">'addresses.csv'</span><span class="p">).</span><span class="nf">split</span><span class="p">(</span><span class="s1">','</span><span class="p">).</span><span class="nf">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:strip</span><span class="p">)</span>
<span class="n">from</span> <span class="o">=</span> <span class="s2">"example@example.com"</span>
<span class="n">smtp</span> <span class="o">=</span> <span class="no">Net</span><span class="o">::</span><span class="no">SMTP</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s1">'smtp.gmail.com'</span><span class="p">,</span> <span class="mi">587</span><span class="p">)</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">enable_starttls</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">start</span><span class="p">(</span><span class="no">Socket</span><span class="p">.</span><span class="nf">gethostname</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="s2">"</span><span class="p">,</span> <span class="s1">'a_password'</span><span class="p">,</span> <span class="ss">:login</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">smtp</span><span class="o">|</span>
<span class="n">addresses</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">to</span><span class="o">|</span>
<span class="n">message</span> <span class="o">=</span> <span class="o">&lt;&lt;</span><span class="no">EOM</span>
<span class="sh">
From: Someone &lt;</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="sh">&gt;
To: Someone2 &lt;</span><span class="si">#{</span><span class="n">to</span><span class="si">}</span><span class="sh">&gt;
Subject: This is from Ruby
Date: </span><span class="si">#{</span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span><span class="p">.</span><span class="nf">strftime</span><span class="p">(</span><span class="s2">"%d/%m/%Y %H:%M"</span><span class="p">)</span><span class="si">}</span><span class="sh">
This email was sent using Ruby
</span><span class="no">EOM
</span>
<span class="k">begin</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="s2">"</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="n">to</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="k">rescue</span> <span class="no">Exception</span> <span class="o">=&gt;</span> <span class="n">e</span>
<span class="nb">puts</span> <span class="n">e</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>So tell me what is wrong with this code? The biggest problem I see is reassigning to the message variable in the each loop (I am sure there is much more wrong, but right now this is the most obvious).</p>
<p>When sending 1 or 2 emails, this might not be a big issue but when you start sending hundreds or thousands, I am pretty sure there will be some cost involved.</p>
<p>Today I did some digging and found that you can do string substitution using the ‘%’ symbol. So instead of using #{varible_name} you can use %{variable_name}</p>
<p>So now my code looks like this:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">require</span> <span class="s1">'net/smtp'</span>
<span class="n">addresses</span> <span class="o">=</span> <span class="no">File</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="s1">'addresses.csv'</span><span class="p">).</span><span class="nf">split</span><span class="p">(</span><span class="s1">','</span><span class="p">).</span><span class="nf">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:strip</span><span class="p">)</span>
<span class="n">from</span> <span class="o">=</span> <span class="s2">"example@example.com"</span>
<span class="n">message</span> <span class="o">=</span> <span class="o">&lt;&lt;</span><span class="no">EOM</span>
<span class="sh">
From: Someone &lt;</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="sh">&gt;
To: Someone2 &lt;%{to}&gt;
Subject: This is from Ruby
Date: </span><span class="si">#{</span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span><span class="p">.</span><span class="nf">strftime</span><span class="p">(</span><span class="s2">"%d/%m/%Y %H:%M"</span><span class="p">)</span><span class="si">}</span><span class="sh">
This email was sent using Ruby
</span><span class="no">EOM
</span>
<span class="n">smtp</span> <span class="o">=</span> <span class="no">Net</span><span class="o">::</span><span class="no">SMTP</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s1">'smtp.gmail.com'</span><span class="p">,</span> <span class="mi">587</span><span class="p">)</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">enable_starttls</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">start</span><span class="p">(</span><span class="no">Socket</span><span class="p">.</span><span class="nf">gethostname</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="s2">"</span><span class="p">,</span> <span class="s1">'a_password'</span><span class="p">,</span> <span class="ss">:login</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">smtp</span><span class="o">|</span>
<span class="n">addresses</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">to</span><span class="o">|</span>
<span class="k">begin</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">message</span> <span class="o">%</span> <span class="p">{</span><span class="ss">to: </span><span class="n">to</span><span class="p">},</span> <span class="s2">"</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="s2">"</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="n">to</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="k">rescue</span> <span class="no">Exception</span> <span class="o">=&gt;</span> <span class="n">e</span>
<span class="nb">puts</span> <span class="n">e</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>So rule of thumb is if you want to reuse a string template by assigning it to a variable and change items within the template in a loop. Or if you want to pass a string template around you should do so using the ‘%’ symbol for string substitution instead.</p>
<p>There are 2 ways to do string substitution using the ‘%’ symbol. You can use an array like below:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">message</span> <span class="o">=</span> <span class="s2">"Hello %s, welcome to %s."</span>
<span class="nb">puts</span> <span class="n">message</span> <span class="o">%</span> <span class="p">[</span><span class="s1">'Guy'</span><span class="p">,</span> <span class="s1">'The Boom Boom Room'</span><span class="p">]</span></code></pre></figure>
<p>Where ‘%s’ is for a string, ‘%f’ would be for float and ‘%d’ is for integer.</p>
<p>The second way and my preference is using a Hash. I prefer this as you can use named placements and there is no need to worry about potential data type errors.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">message</span> <span class="o">=</span> <span class="s2">"Hello %{name}, welcome to %{address}."</span>
<span class="nb">puts</span> <span class="n">message</span> <span class="o">%</span> <span class="p">{</span><span class="ss">name: </span><span class="s1">'Guy'</span><span class="p">,</span> <span class="n">address</span><span class="ss">:'The Boom Boom Room'</span><span class="p">}</span></code></pre></figure>
<p>Pretty sweet right?</p>
<hr />
Sending emails using Ruby with nothing more than the core library and a csv2014-07-21T00:00:00+00:00http://deonheyns.com/posts/sending-emails-using-ruby-with-nothing-more-than-the-core-library-and-a-csv<p>Tonight I wanted to accomplish something easy. Read a list of email addresses from a CSV file and send a generic message to those email addresses.</p>
<p>Here is the code I came up with in about 5 minutes or so.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">require</span> <span class="s1">'net/smtp'</span>
<span class="n">addresses</span> <span class="o">=</span> <span class="no">File</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="s1">'addresses.csv'</span><span class="p">).</span><span class="nf">split</span><span class="p">(</span><span class="s1">','</span><span class="p">).</span><span class="nf">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:strip</span><span class="p">)</span>
<span class="n">from</span> <span class="o">=</span> <span class="s2">"example@example.com"</span>
<span class="n">smtp</span> <span class="o">=</span> <span class="no">Net</span><span class="o">::</span><span class="no">SMTP</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s1">'smtp.gmail.com'</span><span class="p">,</span> <span class="mi">587</span><span class="p">)</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">enable_starttls</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">start</span><span class="p">(</span><span class="no">Socket</span><span class="p">.</span><span class="nf">gethostname</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="s2">"</span><span class="p">,</span> <span class="s1">'a_password'</span><span class="p">,</span> <span class="ss">:login</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">smtp</span><span class="o">|</span>
<span class="n">addresses</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">to</span><span class="o">|</span>
<span class="n">message</span> <span class="o">=</span> <span class="o">&lt;&lt;</span><span class="no">EOM</span>
<span class="sh">
From: Someone &lt;</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="sh">&gt;
To: Someone2 &lt;</span><span class="si">#{</span><span class="n">to</span><span class="si">}</span><span class="sh">&gt;
Subject: This is from Ruby
Date: </span><span class="si">#{</span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span><span class="p">.</span><span class="nf">strftime</span><span class="p">(</span><span class="s2">"%d/%m/%Y %H:%M"</span><span class="p">)</span><span class="si">}</span><span class="sh">
This email was sent using Ruby
</span><span class="no">EOM
</span>
<span class="k">begin</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="s2">"</span><span class="p">,</span> <span class="s2">"</span><span class="si">#{</span><span class="n">to</span><span class="si">}</span><span class="s2">"</span><span class="p">)</span>
<span class="k">rescue</span> <span class="no">Exception</span> <span class="o">=&gt;</span> <span class="n">e</span>
<span class="nb">puts</span> <span class="n">e</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>Look at this:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">addresses</span> <span class="o">=</span> <span class="no">File</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="s1">'addresses.csv'</span><span class="p">).</span><span class="nf">split</span><span class="p">(</span><span class="s1">','</span><span class="p">).</span><span class="nf">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:strip</span><span class="p">)</span></code></pre></figure>
<p>There you go CSV read, and I have an array of the email addresses.</p>
<p>The rest of the code I have already spoken about in this [post][email]. One thing that I am curious about is the message variable. There must be a more efficient way to do that? Though the performance hit right now is tiny I don’t want to get into the habit of writing inefficient / slow code. I only spent around 5 minutes on this and clearly it can be done and should be done better. Therefore, my mission for the rest this week is to find a way to make that bit of code more concise and make the whole loop more efficient.</p>
<p>Did I say I love <a href="https://www.ruby-lang.org/en/">Ruby</a>?!?!?</p>
<p>Right now is also a good time to dive into the many different gems that give you the ability to send an email. I am going to discuss that some more in the coming days and try and figure out in which different scenarios you might prefer one gem over another.</p>
<hr />
C# to Ruby String Interpolation2014-07-20T00:00:00+00:00http://deonheyns.com/posts/csharp-to-ruby-string-interpolation<h3 id="why">Why?</h3>
<p>Working with strings is part and parcel of any programming language. In C#, we use String.Format to do a lot of interpolation and manipulation. Here is a simple example using C#</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">using</span> <span class="no">System</span><span class="p">;</span>
<span class="n">namespace</span> <span class="no">Foo</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="k">class</span> <span class="nc">Program</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="n">void</span> <span class="no">Main</span><span class="p">(</span><span class="n">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">var</span> <span class="nb">name</span> <span class="o">=</span> <span class="s2">"Deon Heyns"</span><span class="p">;</span>
<span class="n">var</span> <span class="n">reallyLike</span> <span class="o">=</span> <span class="s2">"Programming"</span><span class="p">;</span>
<span class="n">var</span> <span class="n">sentence</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="no">Format</span><span class="p">(</span><span class="s2">"Hello my name is {0} and I love {1}"</span><span class="p">,</span> <span class="nb">name</span><span class="p">,</span> <span class="n">reallyLike</span><span class="p">);</span>
<span class="no">Console</span><span class="o">.</span><span class="no">WriteLine</span><span class="p">(</span><span class="n">sentence</span><span class="p">);</span>
<span class="n">var</span> <span class="n">result</span> <span class="o">=</span> <span class="no">Factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="o">*</span> <span class="mi">7</span><span class="p">;</span>
<span class="n">var</span> <span class="n">answer</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="no">Format</span><span class="p">(</span><span class="s2">"The answer is {0}, which is also the answer to everything"</span><span class="p">,</span> <span class="n">result</span><span class="p">);</span>
<span class="no">Console</span><span class="o">.</span><span class="no">WriteLine</span><span class="p">(</span><span class="n">answer</span><span class="p">)</span>
<span class="p">}</span>
<span class="kp">public</span> <span class="n">static</span> <span class="n">int</span> <span class="no">Factorial</span><span class="p">(</span><span class="n">int</span> <span class="n">n</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">?</span> <span class="mi">1</span> <span class="p">:</span> <span class="n">n</span> <span class="o">*</span> <span class="no">Factorial</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<h3 id="how">How?</h3>
<p>Now how do we accomplish the same thing in <a href="https://www.ruby-lang.org/en/">Ruby</a>?</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">name</span> <span class="o">=</span> <span class="s2">"Deon Heyns"</span>
<span class="n">reallyLike</span> <span class="o">=</span> <span class="s2">"Programming"</span>
<span class="n">sentence</span> <span class="o">=</span> <span class="s2">"Hello my name is </span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2"> and I love </span><span class="si">#{</span><span class="n">reallyLike</span><span class="si">}</span><span class="s2">"</span>
<span class="nb">puts</span> <span class="n">sentence</span>
<span class="n">result</span> <span class="o">=</span> <span class="s2">"The answer is </span><span class="si">#{</span> <span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">n</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">?</span> <span class="mi">1</span> <span class="p">:</span> <span class="n">n</span><span class="o">*</span><span class="n">factorial</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="k">end</span>
<span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">*</span><span class="mi">7</span> <span class="si">}</span><span class="s2">, which is also the answer to everything"</span>
<span class="nb">puts</span> <span class="n">results</span></code></pre></figure>
<p>From this code you see we are not using a position within our string to specify what variable goes where, we do this explicitly +1. You can define a method, in the middle of this string! What you might see here is that you need to use double quotes (“) and you use the hash / pound / number sign with curly braces to define a variable. There isn’t too much else to mention here. It’s pretty straight-forward and to me it seems like a better way to add your variables within the string since you don’t need to worry about positioning.</p>
<h3 id="conclusion">Conclusion</h3>
<p><a href="https://www.ruby-lang.org/en/">Ruby</a> strikes again! Again I see that <a href="https://www.ruby-lang.org/en/">Ruby</a> wants you to use fewer key strokes and be more explicit about what you want to do. What an awesome language!</p>
<hr />
How to put your Ruby constructors on a diet2014-07-19T00:00:00+00:00http://deonheyns.com/posts/how-to-put-your-ruby-constructors-on-a-diet<h3 id="why">Why?</h3>
<p>Coming from the .NET world constructors can get pretty messy when passing in more than three parameters to a constructor. The book <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code</a> suggests that you create an object to use as a parameter once the constructor takes more than 3 arguments.</p>
<h3 id="how">How?</h3>
<p>So if we look at this <a href="https://www.ruby-lang.org/en/">Ruby</a> code we can see how messy it is when you have a number of parameters passed to the initialize method. I went digging around in the book <a href="http://www.amazon.com/Ruby-Way-Solutions-Techniques-Programming/dp/0321714636/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1405612762&amp;sr=1-1&amp;keywords=The+ruby+way">The Ruby Way</a> and found what I think is a pretty clean solution</p>
<p>Messy Code:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">PersonalComputer</span>
<span class="nb">attr_accessor</span> <span class="ss">:manufacturer</span><span class="p">,</span>
<span class="ss">:model</span><span class="p">,</span> <span class="ss">:processor</span><span class="p">,</span> <span class="ss">:clock</span><span class="p">,</span>
<span class="ss">:ram</span><span class="p">,</span> <span class="ss">:disk</span><span class="p">,</span> <span class="ss">:monitor</span><span class="p">,</span> <span class="ss">:colors</span><span class="p">,</span>
<span class="ss">:vres</span><span class="p">,</span> <span class="ss">:hres</span><span class="p">,</span> <span class="ss">:net</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">manufacturer</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="n">processor</span><span class="p">,</span>
<span class="n">clock</span><span class="p">,</span> <span class="n">ram</span><span class="p">,</span> <span class="n">disk</span><span class="p">,</span>
<span class="n">monitor</span><span class="p">,</span> <span class="n">colors</span><span class="p">,</span> <span class="n">vres</span><span class="p">,</span>
<span class="n">hres</span><span class="p">,</span> <span class="n">net</span><span class="p">)</span>
<span class="vi">@manufacture</span> <span class="o">=</span> <span class="n">manufacture</span>
<span class="vi">@model</span> <span class="o">=</span> <span class="n">model</span>
<span class="vi">@processor</span> <span class="o">=</span> <span class="n">processor</span>
<span class="vi">@clock</span> <span class="o">=</span> <span class="n">clock</span>
<span class="vi">@ram</span> <span class="o">=</span> <span class="n">ram</span>
<span class="vi">@disk</span> <span class="o">=</span> <span class="n">disk</span>
<span class="vi">@monitor</span> <span class="o">=</span> <span class="n">monitor</span>
<span class="vi">@color</span> <span class="o">=</span> <span class="n">color</span>
<span class="vi">@vres</span> <span class="o">=</span> <span class="n">vres</span>
<span class="vi">@hres</span> <span class="o">=</span> <span class="n">hres</span>
<span class="vi">@net</span> <span class="o">=</span> <span class="n">net</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>Clean code:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">PersonalComputer</span>
<span class="nb">attr_accessor</span> <span class="ss">:manufacturer</span><span class="p">,</span>
<span class="ss">:model</span><span class="p">,</span> <span class="ss">:processor</span><span class="p">,</span> <span class="ss">:clock</span><span class="p">,</span>
<span class="ss">:ram</span><span class="p">,</span> <span class="ss">:disk</span><span class="p">,</span> <span class="ss">:monitor</span><span class="p">,</span> <span class="ss">:colors</span><span class="p">,</span>
<span class="ss">:vres</span><span class="p">,</span> <span class="ss">:hres</span><span class="p">,</span> <span class="ss">:net</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="o">&amp;</span><span class="n">block</span><span class="p">)</span>
<span class="nb">instance_eval</span> <span class="o">&amp;</span><span class="n">block</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>So this looks pretty clear but how do I set the properties using that &amp;block parameter? Let’s have a look at this</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre><span class="n">macbook</span> <span class="o">=</span> <span class="no">PersonalComputer</span><span class="p">.</span><span class="nf">new</span> <span class="k">do</span>
<span class="n">manufacture</span> <span class="o">=</span> <span class="o">=</span> <span class="s1">'Apple'</span>
<span class="n">model</span> <span class="o">=</span> <span class="s1">'Macbook Pro'</span>
<span class="n">processor</span> <span class="o">=</span> <span class="mf">2.6</span> <span class="c1"># GHz
</span>
<span class="n">clock</span> <span class="o">=</span> <span class="mi">16</span> <span class="c1"># Gb
</span>
<span class="n">ram</span> <span class="o">=</span> <span class="mi">16</span> <span class="c1"># Gb
</span>
<span class="n">disk</span> <span class="o">=</span> <span class="mi">500</span> <span class="c1"># Gb
</span>
<span class="n">monitor</span> <span class="o">=</span> <span class="mi">15</span> <span class="c1"># inches
</span>
<span class="n">color</span> <span class="o">=</span> <span class="mi">16777216</span>
<span class="n">vres</span> <span class="o">=</span> <span class="mi">1280</span>
<span class="n">hres</span> <span class="o">=</span> <span class="mi">1600</span>
<span class="n">net</span> <span class="o">=</span> <span class="s1">'T3'</span>
<span class="k">end</span></pre></td></tr></tbody></table></code></pre></figure>
<p>Bam! So to me this looks like an anonymous function. We can do any logic in this block so if we needed to call some service or read some file or database to get this data we could.</p>
<p>Here we see that we use accessors for our attributes that they are assigned to intuitively. Also, you need a reference to self as a setter method always needs an explicit receiver to distinguish the method call from an ordinary assignment to a local variable.</p>
<h3 id="conclusion">Conclusion</h3>
<p>This is a nice way to set our properties, we could always create some object to carry these properties but then we add another class that will need to be maintained and tested. I am not sure how the .NET world would feel about setting properties using a Func<T> but might be a useful tool to keep in the tool-belt.</T></p>
<hr />
Haiku Friday - Pay the Piper2014-07-18T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-pay-the-piper<p>##On the path to riches</p>
<p><img src="http://deonheyns.com/images/money.jpg" alt="Money" /></p>
<p>##You will need much wisdom and</p>
<p><img src="http://deonheyns.com/images/ruby_on_rails_tutorial.jpg" alt="Ruby on Rails" /></p>
<p>##You must pay the piper</p>
<p><img src="http://deonheyns.com/images/michael_hartl.jpeg" alt="Michael Hartl" /></p>
<hr />
Transformation Thursday - C# to Ruby, What is the equivalent of a Class in Ruby2014-07-17T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-class-in-ruby<h3 id="why">Why?</h3>
<p>I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a> and thought it would be useful to other .NET developers coming to <a href="https://www.ruby-lang.org/en/">Ruby</a> to understand the different constructs.</p>
<p>I covered <a href="/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-namespace-in-ruby">Namespaces</a> previously and would like to follow that up with the next logical part Classes.</p>
<p>Let’s look at our previous FancyCalculator code.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">namespace</span> <span class="no">Calculator</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="k">class</span> <span class="nc">FancyCalculator</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="no">FancyCalculator</span><span class="p">()</span>
<span class="p">{</span>
<span class="p">}</span>
<span class="kp">public</span> <span class="n">int</span> <span class="no">Add</span><span class="p">(</span><span class="n">int</span> <span class="n">lhs</span><span class="p">,</span> <span class="n">int</span> <span class="n">rhs</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p>Here we see that our class is the container for our properties and variables. I am not going to spend too much time on this as this is pretty straight-forward C# code</p>
<h3 id="how">How?</h3>
<p>Now let’s take a look at the <a href="https://www.ruby-lang.org/en/">Ruby</a> code and discuss that.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">module</span> <span class="nn">Calculator</span> <span class="c1"># a namespace
</span>
<span class="k">class</span> <span class="nc">FancyCalculator</span> <span class="c1"># a class
</span>
<span class="k">def</span> <span class="nf">initialize</span> <span class="c1"># a constructor
</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># a method in the class
</span>
<span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>Classes in Ruby are first class objects, you will create a new class a little different then you do in C#</p>
<p>C#:</p>
<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">calculator</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Calculator</span><span class="p">();</span>
</code></pre></div></div>
<p>Ruby:</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">calc</span> <span class="o">=</span> <span class="no">FancyCalculator</span><span class="p">.</span><span class="nf">new</span>
</code></pre></div></div>
<p>If you want your constructor to take parameters unlike C# you won’t be creating a new constructor method with the parameters you need. You will rather use the initialize method for your parameters.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">module</span> <span class="nn">Calculator</span> <span class="c1"># a namespace
</span>
<span class="k">class</span> <span class="nc">FancyCalculator</span> <span class="c1"># a class
</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
<span class="vi">@name</span> <span class="o">=</span> <span class="nb">name</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># a method in the class
</span>
<span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>We will dive into constructors a bit more next week. For now, you just need to know that you will need to define an initialize method pass the parameters and then set the properties or do any work you need to with the parameters.</p>
<h3 id="conclusion">Conclusion</h3>
<p>There are two differences when it comes to C# and <a href="https://www.ruby-lang.org/en/">Ruby</a> classes. The one being that you use Class.new instead of new Class() and the other is that you pass your constructor parameters to the initialize method instead of overriding the new method on the class.</p>
<p>Further, then the two differences mentioned class are pretty straight-forward and easy to understand.</p>
<hr />
The easiest way to get Github Pages working with an Alias, AName, A record2014-07-16T00:00:00+00:00http://deonheyns.com/posts/the-easiest-way-to-get-github-pages-working-with-an-alies-or-aname-record<p>I was speaking to a buddy of mine the other day about setting up <a href="https://pages.github.com/">Github pages</a> to work with a custom domain. There are some good docs from <a href="https://github.com">Github</a> on getting this done. However, he struggled and I struggled to get this done before so I am giving you the to the point guide.</p>
<p>So this isn’t post is not on getting Jekyll working or on <a href="https://pages.github.com/">GitHub pages</a> itself this is a to the point guide on getting your custom domain pointing to your *.github.io site.</p>
<ul>
<li>Create or edit the CNAME file that is in your <a href="https://pages.github.com/">GitHub pages</a> repository. There can only be 1 entry. In my case, this was</li>
</ul>
<pre><code class="language-cname">deonheyns.com
</code></pre>
<ul>
<li>Use the ping command to find out what the IP address is for your *.github.io site.</li>
</ul>
<p><img src="http://deonheyns.com/images/ping.png" alt="ping" /></p>
<ul>
<li>Now you are in the money. Head over to whoever is your DNS provider. (btw <a href="https://dnsimple.com/r/71d3fc80908419">DNSimple</a> is pretty awesome to use)</li>
<li>Create an AName, Alias or A record for your site (in my case deonheyns.com) to point to the IP address you got from the ping command.</li>
<li>Wait for the changes to propagate depending on the TTL you have set.</li>
<li>Navigate to your site and do the happy dance.</li>
</ul>
<hr />
C# to Ruby how to send an Email message2014-07-15T00:00:00+00:00http://deonheyns.com/posts/csharp-to-ruby-how-to-send-an-email-message<h3 id="why">Why?</h3>
<p>Many applications need to send emails. Signing up to a website? You get an email. Signing up to a new newsletter? You get an email. There are many other reasons and uses such as sending emails for alerts and so forth.</p>
<h3 id="how">How?</h3>
<p>Let’s compare the different ways to implement the sending of emails using .NET and specifically C# and <a href="https://www.ruby-lang.org/en/">Ruby</a></p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">using</span> <span class="no">System</span><span class="o">.</span><span class="no">Net</span><span class="p">;</span>
<span class="n">using</span> <span class="no">System</span><span class="o">.</span><span class="no">Net</span><span class="o">.</span><span class="no">Mail</span><span class="p">;</span>
<span class="n">namespace</span> <span class="no">MailSender</span>
<span class="p">{</span>
<span class="k">class</span> <span class="nc">Program</span>
<span class="p">{</span>
<span class="n">static</span> <span class="n">void</span> <span class="no">Main</span><span class="p">(</span><span class="n">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">var</span> <span class="n">message</span> <span class="o">=</span> <span class="n">new</span> <span class="no">MailMessage</span><span class="p">(</span><span class="ss">from: </span><span class="s2">"someone@gmail.com"</span><span class="p">,</span> <span class="ss">to: </span><span class="s2">"someone2@gmail.com"</span><span class="p">,</span> <span class="ss">subject: </span><span class="s2">"This is from C#"</span><span class="p">,</span> <span class="ss">body: </span><span class="s2">"This email was sent using .NET"</span><span class="p">);</span>
<span class="n">var</span> <span class="n">smtp</span> <span class="o">=</span> <span class="n">new</span> <span class="no">SmtpClient</span><span class="p">(</span><span class="s2">"smtp.gmail.com"</span><span class="p">,</span> <span class="mi">587</span><span class="p">);</span>
<span class="n">smtp</span><span class="o">.</span><span class="no">EnableSsl</span> <span class="o">=</span> <span class="kp">true</span><span class="p">;</span>
<span class="n">smtp</span><span class="o">.</span><span class="no">Credentials</span> <span class="o">=</span> <span class="n">new</span> <span class="no">NetworkCredential</span><span class="p">(</span><span class="ss">userName: </span><span class="s2">"someone@gmail.com"</span><span class="p">,</span> <span class="ss">password: </span><span class="s2">"a_password"</span><span class="p">);</span>
<span class="n">smtp</span><span class="o">.</span><span class="no">Send</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p>We need 2 using statements, 1 to System.Net the other to System.Net.Mail. We instantiate a new MailMessage object with our content. We use the built-in Smtp class and set the host and port number. Since we are using Gmail to send this email, we need to ensure we have a secure connection and do so by setting the EnableSsl flag to true. We then go ahead and set our Credentials and call Send passing in our MailMessage object.</p>
<p>Now in <a href="https://www.ruby-lang.org/en/">Ruby</a></p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="c1"># http://ruby-doc.org/stdlib-2.0/libdoc/net/smtp/rdoc/Net/SMTP.html
</span>
<span class="nb">require</span> <span class="s1">'net/smtp'</span>
<span class="n">from</span> <span class="o">=</span> <span class="n">someone</span><span class="vi">@gmail</span><span class="p">.</span><span class="nf">com</span>
<span class="n">to</span> <span class="o">=</span> <span class="n">someone2</span><span class="vi">@gmail</span><span class="p">.</span><span class="nf">com</span>
<span class="n">message</span> <span class="o">=</span> <span class="o">&lt;&lt;</span><span class="no">EOM</span>
<span class="sh">
From: Someone &lt;</span><span class="si">#{</span><span class="n">from</span><span class="si">}</span><span class="sh">&gt;
To: Someone2 &lt;</span><span class="si">#{</span><span class="n">to</span><span class="si">}</span><span class="sh">&gt;
Subject: This is from Ruby
Date: </span><span class="si">#{</span><span class="no">Time</span><span class="p">.</span><span class="nf">now</span><span class="p">.</span><span class="nf">strftime</span><span class="p">(</span><span class="s2">"%d/%m/%Y %H:%M"</span><span class="p">)</span><span class="si">}</span><span class="sh">
This email was sent using Ruby
</span><span class="no">EOM
</span>
<span class="n">smtp</span> <span class="o">=</span> <span class="no">Net</span><span class="o">::</span><span class="no">SMTP</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="s1">'smtp.gmail.com'</span><span class="p">,</span> <span class="mi">587</span><span class="p">)</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">enable_starttls</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">start</span><span class="p">(</span><span class="no">Socket</span><span class="p">.</span><span class="nf">gethostname</span><span class="p">,</span> <span class="s1">'#{from}'</span><span class="p">,</span> <span class="s1">'a_password'</span><span class="p">,</span> <span class="ss">:login</span><span class="p">)</span> <span class="k">do</span> <span class="o">|</span><span class="n">smtp</span><span class="o">|</span>
<span class="n">smtp</span><span class="p">.</span><span class="nf">send_message</span><span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="s1">'#{from}'</span><span class="p">,</span> <span class="s1">'#{to}'</span><span class="p">)</span>
<span class="k">end</span></code></pre></figure>
<p>Again I prefer to use built-in functionality, so there is a require to ‘net/smtp’ to pull in the classes we are going to need. The code is pretty straight forward with the exception of having to create the message format by hand including the From, To and Subject fields. The only thing I really got stumped by was how to enable the secure tls transportation which is accomplished by</p>
<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">smtp</span><span class="p">.</span><span class="nf">enable_starttls</span>
</code></pre></div></div>
<p>To figure that out I just had to read the <a href="http://ruby-doc.org/stdlib-2.0/libdoc/net/smtp/rdoc/Net/SMTP.html">SMTP</a> docs which are pretty helpful.</p>
<h3 id="conclusion">Conclusion</h3>
<p>Both approaches are pretty straightforward the only thing I really had a hard time with was enabling tls in the <a href="https://www.ruby-lang.org/en/">Ruby</a> implementation but I was able quickly to sort that out.</p>
<p>Hopefully, this will help someone in the future and again even if that someone is me!</p>
<hr />
Get Rails working with Postgresql2014-07-14T00:00:00+00:00http://deonheyns.com/posts/get-rails-working-with-postgresql<p>Tonight I was banging my head against the wall trying to get my <a href="http://rubyonrails.org/">Rails</a> application to use <a href="http://www.postgresql.org/">Postgres</a> for Test and Development.</p>
<p>Initially, I thought “sure no problem how hard could this be.” I read up in my copy of <a href="http://www.amazon.com/Rails-Edition-Addison-Wesley-Professional-Series/dp/0321944275/">The Rails 4 Way</a> which had most of the configuration I needed. Here was me doing a happy dance that I was able to cross off 1 of the exercises from the <a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a> man I was super excited.</p>
<p>So I filled in the yaml and ran</p>
<pre><code class="language-cmd">$ rake db:setup
</code></pre>
<p>The message I got was a BIG</p>
<p><img src="http://deonheyns.com/images/fuu.jpg" alt="fuu" /></p>
<p>I thought okay this can’t be this hectic and started searching and searching and searching. I re-read the error message, and it was complaining something along the lines of “is postgresql installed?”</p>
<p>At that point, I decided “screw this” and went for a walk. When I got back home I decided to have another bash. I tried to find any page or post that had the different variables applicable in a database.yml file and found nothing.</p>
<p>Then on a whim I decided to add</p>
<div class="language-yml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">host</span><span class="pi">:</span> <span class="s">localhost</span>
</code></pre></div></div>
<p>reran</p>
<pre><code class="language-cmd">$ rake db:setup
</code></pre>
<p>It worked!!! So again I am going to post my configuration so that if anyone ever (even me) runs into this there is a solution to getting <a href="http://www.postgresql.org/">Postgresql</a> working with your <a href="http://rubyonrails.org/">Rails</a> environment.</p>
<p>Here is my database.yml file</p>
<div class="language-yml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">default</span><span class="pi">:</span> <span class="nl">&amp;default</span>
<span class="na">host</span><span class="pi">:</span> <span class="s">localhost</span>
<span class="na">adapter</span><span class="pi">:</span> <span class="s">postgresql</span>
<span class="na">encoding</span><span class="pi">:</span> <span class="s">unicode</span>
<span class="na">pool</span><span class="pi">:</span> <span class="s">5</span>
<span class="na">username</span><span class="pi">:</span> <span class="s">postgres</span>
<span class="na">password</span><span class="pi">:</span> <span class="s">work!1234</span>
<span class="na">development</span><span class="pi">:</span>
<span class="s">&lt;&lt;</span><span class="pi">:</span> <span class="nv">*default</span>
<span class="na">database</span><span class="pi">:</span> <span class="s">sample_app_dev</span>
<span class="na">test</span><span class="pi">:</span>
<span class="s">&lt;&lt;</span><span class="pi">:</span> <span class="nv">*default</span>
<span class="na">database</span><span class="pi">:</span> <span class="s">sample_app_test</span>
</code></pre></div></div>
<hr />
An introduction to Rails - Ruby on Rails Tutorial by Michael Hartl2014-07-13T00:00:00+00:00http://deonheyns.com/posts/ruby-on-rails-tutorial<p>Earlier this week I started going through the <a href="http://www.railstutorial.org/">Ruby On Rails Tutorial</a> by Michael Hartl. The book is freely available at <a href="http://www.railstutorial.org/">http://www.railstutorial.org/</a>. The book states that it answers the questions “If <a href="/posts/rails-here-is-my-plan-to-learn-ruby">I want to learn</a> web development with <a href="http://rubyonrails.org/">Ruby on Rails</a>, where should I start?” and this is exactly the question I have asked myself and searched around for.</p>
<p>The book us made up of the following 11 Chapters:</p>
<ul>
<li>Chapter 1 From zero to deploy</li>
<li>Chapter 2 A demo app</li>
<li>Chapter 3 Mostly static pages</li>
<li>Chapter 4 Rails-flavored Ruby</li>
<li>Chapter 5 Filling in the layout</li>
<li>Chapter 6 Modeling users</li>
<li>Chapter 7 Sign up</li>
<li>Chapter 8 Sign in, sign out</li>
<li>Chapter 9 Updating, showing, and deleting users</li>
<li>Chapter 10 User microposts</li>
<li>Chapter 11 Following users</li>
</ul>
<p>In my mind, these chapters cover most of the common use-cases that appear in Web applications namely</p>
<ul>
<li>Static Pages</li>
<li>Dynamic Pages</li>
<li>CSS</li>
<li>Models</li>
<li>Authentication and Authorization</li>
</ul>
<p>So far I have gotten to Chapter 4 (not any further as I have a <a href="/posts/on-the-importance-of-rest">no “code rule” for Sundays</a>), and I am very pleased. I have already deployed 3 applications to <a href="https://www.heroku.com">Heroku</a>, learnt some git commands I didn’t know and been compelled to dig somewhat into <a href="/posts/handy-rvm-commands">RVM</a>.</p>
<p>I like the approach of not using the scaffolding functions baked into <a href="http://rubyonrails.org/">Rails</a> that the book employs from Chapter 3 onwards; this means you get to know how <a href="http://rubyonrails.org/">Rails</a> works and can better understand how things piece together.</p>
<p>So, so far so good I am happy with the tutorial and hope to be finished with Chapter 5 by tomorrow. I suggest that if you are learning <a href="http://rubyonrails.org/">Rails</a> that you go through this <a href="http://www.railstutorial.org/">tutorial</a>, you will be doing yourself a massive favor.</p>
<hr />
Handy RVM Commands2014-07-12T00:00:00+00:00http://deonheyns.com/posts/handy-rvm-commands<h3 id="why">Why?</h3>
<p>I’m <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a>! Its fun and today I was exploring <a href="https://rvm.io/">RVM</a>. <a href="https://rvm.io/">RVM</a> is somewhat like NuGet but for <a href="https://www.ruby-lang.org/en/">Ruby</a>.</p>
<h3 id="how">How?</h3>
<p><a href="https://rvm.io/">RVM</a> needs to be installed, and you can do so using</p>
<pre><code class="language-rvm">\curl -ssl https://get.rvm.io | bash -s stable --ruby
</code></pre>
<p>There is a backslash before the curl command this prevents any issues if you may have aliased it with configuration in your ~/.curlrc file.</p>
<p>This command will install both <a href="https://rvm.io/">RVM</a> and <a href="https://www.ruby-lang.org/en/">Ruby</a>, so with this one command your machine will have both <a href="https://www.ruby-lang.org/en/">Ruby</a> and <a href="https://rvm.io/">RVM</a> ready for use.</p>
<p>Great now that you have <a href="https://rvm.io/">RVM</a> lets perform some tasks</p>
<p>Want another version of <a href="https://www.ruby-lang.org/en/">Ruby</a> on your machine?</p>
<pre><code class="language-rvm">$ rvm install 2.0.0
</code></pre>
<p>What versions of <a href="https://www.ruby-lang.org/en/">Ruby</a> do you have?</p>
<pre><code class="language-rvm">$ rvm list
</code></pre>
<p>This will return a list similar to</p>
<pre><code class="language-rvm">$ rvm rubies
ruby-2.0.0-p195 [ x86_64 ]
=* ruby-2.0.0-p481 [ x86_64 ]
ruby-2.1.0 [ x86_64 ]
# =&gt; - current
# =* - current &amp;&amp; default
# * - default
</code></pre>
<p>What different versions of <a href="https://www.ruby-lang.org/en/">Ruby</a> are there in the whole wide world?</p>
<pre><code class="language-rvm">$ rvm list known
</code></pre>
<p>Here is a small list of what was available for me to download</p>
<pre><code class="language-rvm"> MRI Rubies
[ruby-]1.8.6[-p420]
[ruby-]1.8.7[-head] # security released on head
[ruby-]1.9.1[-p431]
[ruby-]1.9.2[-head] # security released on head
[ruby-]1.9.3[-p547]
[ruby-]2.0.0-p451
[ruby-]2.0.0[-p481]
[ruby-]2.1.1
[ruby-]2.1[.2]
[ruby-]2.1-head
ruby-head
</code></pre>
<p>How do I change the version of <a href="https://www.ruby-lang.org/en/">Ruby</a> I am currently using?
Let’s say you are using 2.0.0-p195 and want to use 2.1.0.</p>
<pre><code class="language-rvm">$ rvm use ruby-2.1.0
</code></pre>
<p><a href="https://rvm.io/">RVM</a> is updated frequently, to get the latest version run</p>
<pre><code class="language-rvm">$ rvm get stable
</code></pre>
<p>##Gemsets</p>
<p>Gemsets are self-contained collections of gems, this means you can have many of the same gems at different versions and this won’t clash.</p>
<p>To create a gemset just type</p>
<pre><code class="language-gemset">$ rvm gemset create some_name
</code></pre>
<p>To use this all you need to do is</p>
<pre><code class="language-gemset">$ rvm gemset use some_name
</code></pre>
<p>What gemsets are available on my machine?</p>
<pre><code class="language-gemset">rvm gemset list
</code></pre>
<p>Then you can go mad and install your gems! Whats is awesome is that you don’t need to worry about clashes.</p>
<h3 id="conclusion">Conclusion</h3>
<p>I am writing this down because I will forget all this information and need a reference. I am hoping this will help someone someday even if that someone is me!</p>
<hr />
Haiku Friday - Why's (Poignant) Guide To Ruby2014-07-11T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-whys-poignant-guide-to-ruby<p>##Why’s (Poignant) Guide To Ruby</p>
<p><img src="http://deonheyns.com/images/whys.jpg" alt="why" /></p>
<p>##The craziest tutorial on Ruby</p>
<p><img src="http://deonheyns.com/images/ruby.png" alt="ruby" /></p>
<p>##Fills you up inside</p>
<p><img src="http://deonheyns.com/images/cavity.jpg" alt="cavity" /></p>
<hr />
Transformation Thursday - C# to Ruby, What is the equivalent of a Namespace in Ruby2014-07-10T00:00:00+00:00http://deonheyns.com/posts/transformation-thursday-moving-from-csharp-to-ruby-what-is-the-equivalent-of-a-namespace-in-ruby<p>I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a>, and when I look at a C# class file, I always see using statements, a namespace declaration, a class declaration and methods. So what is the equivalent of a namespace in <a href="https://www.ruby-lang.org/en/">Ruby</a>? In other words how to I group a whole bunch of classes into a namespace that I can ship and then will prevent clashes?</p>
<p>Enter the module keyword. A module is a collection of methods and constants. It can group together a bunch of classes and is effectively the equivalent of a namespace in C#.</p>
<p>First here is some C# code that we will work with:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">namespace</span> <span class="no">Calculator</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="k">class</span> <span class="nc">FancyCalculator</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="no">FancyCalculator</span><span class="p">()</span>
<span class="p">{</span>
<span class="p">}</span>
<span class="kp">public</span> <span class="n">int</span> <span class="no">Add</span><span class="p">(</span><span class="n">int</span> <span class="n">lhs</span><span class="p">,</span> <span class="n">int</span> <span class="n">rhs</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p>Here is how you structure the code using a module.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">module</span> <span class="nn">Calculator</span> <span class="c1"># a namespace
</span>
<span class="k">class</span> <span class="nc">FancyCalculator</span> <span class="c1"># a class
</span>
<span class="k">def</span> <span class="nf">initialize</span> <span class="c1"># a constructor
</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">lhs</span><span class="p">,</span> <span class="n">rhs</span><span class="p">)</span> <span class="c1"># a method in the class
</span>
<span class="n">lhs</span> <span class="o">+</span> <span class="n">rhs</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>I will be discussing the other parts of this structure in the coming weeks but for now you should be set. The code above is comparable with C# code so it should be easy to see what is going on.</p>
<p>That everyone is the namespace equivalent in <a href="https://www.ruby-lang.org/en/">Ruby</a>. I will also discuss module some more in the coming days, so stay tuned.</p>
<hr />
C# to Ruby how to Base64 Encode2014-07-09T00:00:00+00:00http://deonheyns.com/posts/csharp-to-ruby-how-to-base64-encode<h3 id="why">Why?</h3>
<p>Today I needed to <a href="http://en.wikipedia.org/wiki/Base64">Base64</a> encode a string, so this was a great opportunity to learn how you would do this in <a href="https://www.ruby-lang.org/en/">Ruby</a> vs. C#</p>
<h3 id="how">How?</h3>
<p>Let’s look at the C# way to do this</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">using</span> <span class="no">System</span><span class="o">.</span><span class="no">Text</span><span class="p">;</span>
<span class="n">namespace</span> <span class="no">Foo</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="k">class</span> <span class="nc">Bar</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="n">string</span> <span class="no">Base64Encode</span><span class="p">(</span><span class="n">string</span> <span class="n">str</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">var</span> <span class="n">bytes</span> <span class="o">=</span> <span class="no">Encoding</span><span class="o">.</span><span class="no">UTF8</span><span class="o">.</span><span class="no">GetBytes</span><span class="p">(</span><span class="n">str</span><span class="p">);</span>
<span class="n">var</span> <span class="n">base64</span> <span class="o">=</span> <span class="no">Convert</span><span class="o">.</span><span class="no">ToBase64String</span><span class="p">(</span><span class="n">bytes</span><span class="p">);</span>
<span class="k">return</span> <span class="n">base64</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p>So I need a using to System.Text, I need to get the string as bytes and the I can convert it to a <a href="http://en.wikipedia.org/wiki/Base64">base64</a> encoded string.</p>
<p>Now how do I do this in <a href="https://www.ruby-lang.org/en/">Ruby</a>?</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="nb">require</span> <span class="s1">'base64'</span>
<span class="k">class</span> <span class="nc">Foo</span>
<span class="k">def</span> <span class="nf">base64_encode</span><span class="p">(</span><span class="n">str</span><span class="p">)</span>
<span class="no">Base64</span><span class="p">.</span><span class="nf">encode64</span><span class="p">(</span><span class="n">str</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>WAT!?!? I need the a require to base64 and then I can call Base64.encode64, there is not much more to say other than wow. <a href="https://www.ruby-lang.org/en/">Ruby</a> again is saving me a whole bunch of keystrokes, and I don’t need to write any extension method this is all baked into the framework.</p>
<h3 id="conclusion">Conclusion</h3>
<p>I’m not totally surprised that this was easier in Ruby however I am amazed at how much easier my life is when using <a href="https://www.ruby-lang.org/en/">Ruby</a>.</p>
<hr />
Keeping to a plan why is it so hard?2014-07-08T00:00:00+00:00http://deonheyns.com/posts/keeping-to-a-plan-why-is-it-so-hard<p>Why would you want to stick to plans? Who cares about so predefined set of goals or milestones? Why did I even set them in the first place?</p>
<p>So why after following a plan for a few days do these questions haunt us? Well, in the book Sidetracked by Francesca Gino she lists three reasons:</p>
<ol>
<li>forces from within ourselves,</li>
<li>forces from our relationships with others,</li>
<li>and forces from the outside world.</li>
</ol>
<p>Have you heard about the <a href="http://rubiquity.com/2013/11/15/impostor-syndrome.html">Impostor Syndrome</a>? It’s a condition where you have a lot of self-doubts. These are the little voices that say we aren’t good enough. How can you overcome this? Look back at your week, month, year or career and remember all the awesome things you have done. Reflect on where your career has taken you, the skills you have learned, projects you have completed or anything else you have done lately. You will quickly release that you are not a fraud.</p>
<p>We are social beings and unfortunately what people say to and about us affects us. Its crap and sucks big ones so what can we do about it? You have gotten this far in your life and overcome numerous obstacles. Sticking to a plan is easy. It’s especially easy when you have a well-<a href="/posts/how-to-set-your-goals-the-right-way">defined plan</a> that includes <a href="/posts/setting-proper-deadlines">milestones</a> and metrics.</p>
<p>Life happens, relationships end, you will experience financial difficulty. These are facts of life and you need to make the most of it. Something to remember is that you learn something through every experience.</p>
<p>These 3 reasons all contribute to making it difficult to stick to our plans. Your job is to keep your focus on what the end goal is. You should also make sure your plan is <a href="/posts/how-to-set-your-goals-the-right-way">realistic and achievable</a>. Nothing is more self-defeating than a plan that is not realistic. Create milestones and track them daily. All of this will help you to keep your head down and keep trucking.</p>
<p>I am no self-help guru. I am just a developer that is learning new things and sharing. These techniques have helped me thus far, and they continue to add value to my life each day.</p>
<hr />
Taking stock of where I am on my journey to learning Ruby and Rails2014-07-07T00:00:00+00:00http://deonheyns.com/posts/taking-stock-of-where-i-am-on-my-journey-to-learning-ruby-and-rails<p>I thought this would be a good time to jot down where I am in terms of my learning. I am doing so mainly because I did not get a chance today to write some <a href="https://www.ruby-lang.org/en/">Ruby</a>, which makes me a sad panda.</p>
<p>So what have I done thus far?</p>
<ul>
<li><a href="http://pluralsight.com/training/Courses/TableOfContents/ruby-rails-dotnet">Ruby on Rails - A Jumpstart for .NET Developers</a></li>
<li><a href="http://pluralsight.com/training/Courses/TableOfContents/play-by-play-aaroncorey">Play by Play: Aaron Patterson and Corey Haines</a></li>
<li><a href="http://pluralsight.com/training/Courses/TableOfContents/ruby-fundamentals">Ruby Fundaments</a></li>
<li><a href="http://koans.heroku.com/">Ruby Koans</a></li>
</ul>
<p>Currently, I am busy with</p>
<ul>
<li><a href="http://www.railstutorial.org/">The Ruby on Rails Tutorial</a></li>
<li><a href="http://mislav.uniqpath.com/poignant-guide/">Why’s (poignant) guide to Ruby</a></li>
</ul>
<p>So I have covered some ground, and I think I feel comfortable enough with my <a href="https://www.ruby-lang.org/en/">Ruby</a> chops to progress onto <a href="http://rubyonrails.org/">Rails</a>. I am having a lot of fun in this <a href="/posts/rails-here-is-my-plan-to-learn-ruby">journey</a>, and I feel happy with my progress at the moment.</p>
<p>Hopefully, for the rest of this week I can get some more learning in and share more on this path I am traveling.</p>
<hr />
Ruby Koans - My Thoughts on completing The Ruby Koans2014-07-06T00:00:00+00:00http://deonheyns.com/posts/ruby-koans-my-thoughts-on-completing-the-ruby-koans<h3 id="why">Why?</h3>
<p>A koan is a story, dialogue, question, or statement, which is used in Zen practice to provoke the “great doubt” and test a student’s progress in Zen practice.</p>
<p>The <a href="http://rubykoans.com/">Ruby Koans</a> asks you questions in the form of unit tests as you learn <a href="https://www.ruby-lang.org/en/">Ruby</a>.</p>
<h3 id="how">How?</h3>
<p>Here is an example</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">test_assert_equality</span>
<span class="n">expected_value</span> <span class="o">=</span> <span class="p">?</span>
<span class="n">actual_value</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">+</span> <span class="mi">1</span>
<span class="n">assert</span> <span class="n">expected_value</span> <span class="o">==</span> <span class="n">actual_value</span>
<span class="k">end</span></code></pre></figure>
<p>You replace the “?” with the answer to ensure the test passes.</p>
<h3 id="conclusion">Conclusion</h3>
<p>I finished the Ruby Koans over the weekend (later than <a href="/posts/rails-here-is-my-plan-to-learn-ruby">anticipated</a>), and I highly recommend them. What was great about the Koans is that its not just simple tests that you need to make sure pass.</p>
<p>There are a few Koans where you get into some deepish Ruby. The Koans teach you about modules, classes, methods, blocks and control statements, this is a great way for anyone to learn <a href="https://www.ruby-lang.org/en/">Ruby</a>.</p>
<p>The Koans are not just for anyone new to programming. I also appreciated how the Koans don’t force you to answer in “The Ruby Way” but rather invoke that curiosity that you end up researching a Koan in order to find the idiomatic way of solving the issue.</p>
<p>So next on <a href="/posts/rails-here-is-my-plan-to-learn-ruby">my plan</a> is to read <a href="http://mislav.uniqpath.com/poignant-guide/">Why’s (poignant) guide to Ruby</a> that I already started and will write about this week, and I will also start out on <a href="http://www.railstutorial.org/">The Ruby on Rails Tutorial</a>. I am excited for both however this week, I am away in Nashville and will need to be very disciplined to make sure I stick to my plan.</p>
<hr />
C# to Ruby - Proxies2014-07-05T00:00:00+00:00http://deonheyns.com/posts/csharp-to-ruby-proxies<h3 id="why">Why?</h3>
<p>I am <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning</a> <a href="https://www.ruby-lang.org/en/">Ruby</a>, and one why I am doing so is with the <a href="http://rubykoans.com/">Ruby Koans</a>. Tonight I completed the Koan: “About Proxy Object Project.”</p>
<p>What is a proxy and why would you want to implement one? In its simplest form, a proxy is an interface or middleman to something else this could be anything: the file-system, the network or any other resource. A common use of a proxy is for intercepting calls and logging them. You can read more on <a href="http://en.wikipedia.org/wiki/Proxy_pattern">Wikipedia</a>.</p>
<h3 id="how">How?</h3>
<p>You need the class you want to proxy and the proxy class implementation that will intercept the calls do something and then invoke the desired method call. I would like to compare the C# implementation and the Ruby implementation.</p>
<p>Let’s start with the C# implementation. I got this from <a href="http://stackoverflow.com/questions/15733900/dynamically-creating-a-proxy-class">StackOverflow</a>:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">using</span> <span class="no">System</span><span class="o">.</span><span class="no">Runtime</span><span class="o">.</span><span class="no">Remoting</span><span class="o">.</span><span class="no">Proxies</span><span class="o">.</span><span class="no">RealProxy</span><span class="p">;</span>
<span class="n">namespace</span> <span class="no">Proxy</span>
<span class="p">{</span>
<span class="kp">public</span> <span class="k">class</span> <span class="nc">LoggingProxy</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span> <span class="p">:</span> <span class="no">RealProxy</span>
<span class="p">{</span>
<span class="kp">private</span> <span class="n">readonly</span> <span class="no">T</span> <span class="n">_instance</span><span class="p">;</span>
<span class="kp">private</span> <span class="no">LoggingProxy</span><span class="p">(</span><span class="no">T</span> <span class="n">instance</span><span class="p">)</span>
<span class="p">:</span> <span class="n">base</span><span class="p">(</span><span class="n">typeof</span><span class="p">(</span><span class="no">T</span><span class="p">))</span>
<span class="p">{</span>
<span class="n">_instance</span> <span class="o">=</span> <span class="n">instance</span><span class="p">;</span>
<span class="p">}</span>
<span class="kp">public</span> <span class="n">static</span> <span class="no">T</span> <span class="no">Create</span><span class="p">(</span><span class="no">T</span> <span class="n">instance</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="p">(</span><span class="no">T</span><span class="p">)</span><span class="n">new</span> <span class="no">LoggingProxy</span><span class="o">&lt;</span><span class="no">T</span><span class="o">&gt;</span><span class="p">(</span><span class="n">instance</span><span class="p">)</span><span class="o">.</span><span class="no">GetTransparentProxy</span><span class="p">();</span>
<span class="p">}</span>
<span class="kp">public</span> <span class="n">override</span> <span class="no">IMessage</span> <span class="no">Invoke</span><span class="p">(</span><span class="no">IMessage</span> <span class="n">msg</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">var</span> <span class="n">methodCall</span> <span class="o">=</span> <span class="p">(</span><span class="no">IMethodCallMessage</span><span class="p">)</span><span class="n">msg</span><span class="p">;</span>
<span class="n">var</span> <span class="nb">method</span> <span class="o">=</span> <span class="p">(</span><span class="no">MethodInfo</span><span class="p">)</span><span class="n">methodCall</span><span class="o">.</span><span class="no">MethodBase</span><span class="p">;</span>
<span class="n">try</span>
<span class="p">{</span>
<span class="no">Console</span><span class="o">.</span><span class="no">WriteLine</span><span class="p">(</span><span class="s2">"Before invoke: "</span> <span class="o">+</span> <span class="nb">method</span><span class="o">.</span><span class="no">Name</span><span class="p">);</span>
<span class="n">var</span> <span class="n">result</span> <span class="o">=</span> <span class="nb">method</span><span class="o">.</span><span class="no">Invoke</span><span class="p">(</span><span class="n">_instance</span><span class="p">,</span> <span class="n">methodCall</span><span class="o">.</span><span class="no">InArgs</span><span class="p">);</span>
<span class="no">Console</span><span class="o">.</span><span class="no">WriteLine</span><span class="p">(</span><span class="s2">"After invoke: "</span> <span class="o">+</span> <span class="nb">method</span><span class="o">.</span><span class="no">Name</span><span class="p">);</span>
<span class="k">return</span> <span class="n">new</span> <span class="no">ReturnMessage</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">null</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">methodCall</span><span class="o">.</span><span class="no">LogicalCallContext</span><span class="p">,</span> <span class="n">methodCall</span><span class="p">);</span>
<span class="p">}</span>
<span class="kp">catch</span> <span class="p">(</span><span class="no">Exception</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
<span class="no">Console</span><span class="o">.</span><span class="no">WriteLine</span><span class="p">(</span><span class="s2">"Exception: "</span> <span class="o">+</span> <span class="n">e</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">e</span> <span class="n">is</span> <span class="no">TargetInvocationException</span> <span class="o">&amp;&amp;</span> <span class="n">e</span><span class="o">.</span><span class="no">InnerException</span> <span class="o">!=</span> <span class="n">null</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">return</span> <span class="n">new</span> <span class="no">ReturnMessage</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="no">InnerException</span><span class="p">,</span> <span class="n">msg</span> <span class="n">as</span> <span class="no">IMethodCallMessage</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">return</span> <span class="n">new</span> <span class="no">ReturnMessage</span><span class="p">(</span><span class="n">e</span><span class="p">,</span> <span class="n">msg</span> <span class="n">as</span> <span class="no">IMethodCallMessage</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span></code></pre></figure>
<p>Let us examine this code to understand what is going on. The first thing we see is we need to add a reference and using statement to System.Runtime.Remoting.Proxies.RealProxy in order to inherit from RealProxy. The LoggingProxy is generic which will give us type safety. The class is a Singleton since it has a private constructor and needs to be created using the Create factory method. Finally, there is the Invoke method that will get called whenever a method is called on our proxied class that will do some logging for us and has some exception handling to ensure we don’t fall over ourselves.</p>
<p>Now to use the proxy class all you would need to do is:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="no">ICalculator</span> <span class="n">calculator</span> <span class="o">=</span> <span class="no">LoggingProxy</span><span class="o">&lt;</span><span class="no">ICalculator</span><span class="o">&gt;.</span><span class="no">Create</span><span class="p">(</span><span class="n">new</span> <span class="no">Calculator</span><span class="p">());</span>
<span class="n">calculator</span><span class="o">.</span><span class="no">Add</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">);</span></code></pre></figure>
<p>Pretty simple, right? Nothing spectacular, there is some casting going on to ensure we get our method, but in terms of complexity not quite hectic? Well maybe…are you ever going to remember this by heart?</p>
<p>Let’s contrast that with how the Rubyists do this sort of thing</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">class</span> <span class="nc">Proxy</span>
<span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">target_object</span><span class="p">)</span>
<span class="vi">@object</span> <span class="o">=</span> <span class="n">target_object</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">method_missing</span><span class="p">(</span><span class="n">method_name</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">block</span><span class="p">)</span>
<span class="k">begin</span>
<span class="nb">puts</span> <span class="s1">'Before Invoke '</span> <span class="o">+</span> <span class="n">method_name</span>
<span class="vi">@object</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="n">method_name</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">block</span><span class="p">)</span>
<span class="nb">puts</span> <span class="s1">'After Invoke '</span> <span class="o">+</span> <span class="n">method_name</span>
<span class="k">rescue</span> <span class="no">NameError</span> <span class="o">=&gt;</span> <span class="n">ex</span>
<span class="nb">puts</span> <span class="s1">'Exception '</span> <span class="o">+</span> <span class="n">ex</span><span class="p">.</span><span class="nf">message</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>Again let’s walk through this code. First thing is that Ruby is a dynamic language and therefore we don’t have a generic class that will ‘Strongly’ type our proxied class. We have initialize that takes an instance of our object that will be proxied, so there is no Create factory method. Also, no private constructor so this is not a singleton. We then extend the method_missing method do our logging in a begin rescue block and proxy off to our class the method that was called together with any args or blocks.</p>
<p>Now how would you use this?</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">calculator</span> <span class="o">=</span> <span class="no">Proxy</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="no">Calculator</span><span class="p">.</span><span class="nf">new</span><span class="p">)</span>
<span class="n">calculator</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span></code></pre></figure>
<p>Wow, that is a quite a bit of typing. I much prefer the Ruby approach which saves a lot of keystrokes. I am not going to declare that one is better or superior to the other. Ruby and C# are two different languages with different strengths and weaknesses. But damn I know which I would rather want to use.</p>
<h3 id="conclusion">Conclusion</h3>
<p>In conclusion, its pretty clear that C# takes a long winded approach to creating proxies, and this is not very obvious to implement. The Ruby approach whilst very concise doesn’t give you the security of type safety. Personally I would prefer to write the Ruby code as it is a lot more straightforward and much easier on the eyes.</p>
<p>I am going to try and do these comparisons regularly. If anything its a way for me to learn more about both languages</p>
<hr />
Haiku Friday - Ruby Koans2014-07-04T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-ruby-koans<p>##Mastering Ruby Koans</p>
<p><img src="http://deonheyns.com/images/enso.gif" alt="Enso" /></p>
<p>##In the quest to be a Ruby Master</p>
<p><img src="http://deonheyns.com/images/samurai.jpg" alt="Samurai" /></p>
<p>##Enlightment they bring
<img src="http://deonheyns.com/images/yoga-kitty.jpg" alt="Yoga Kitty" />
—</p>
On the importance of rest2014-07-03T00:00:00+00:00http://deonheyns.com/posts/on-the-importance-of-rest<p>##You are not a machine!</p>
<p>You need rest; you need to recharge and you need to time for yourself!</p>
<h3 id="why">Why?</h3>
<p>If you want to remain at your peak and achieve efficiency, you need to rest. You need to respect your body and keep your sanity. I once heard a story about a developer that would work crazy hours; the guy was amazing he would churn out software at a phenomenal rate. Then one day he lost it, he lost it bad. This poor guy was unhealthy physically and mentally.</p>
<p>Earlier in my career this was my strategy too. I would sometimes pull all-nighters, be a hero but I quickly learned that doing so on the regular would be catastrophic. I saw the effects on my mood and my health so I quickly started to cut back.</p>
<p>I knew I needed to do something different.</p>
<h3 id="how">How?</h3>
<p>The first thing I done was to start focusing more on delivering between 8am and 6pm. Yes, I would be still be working more than required but at least I would be in bed before 3am. To achieve this, I use the Pomodoro technique, some days I use work sessions where I will block off an hour and concentrate on that, and I make heavy use of a <a href="/post/being-productive-or-trying-to-be-atleast">pen and paper</a>. Second I started eating better, less junk food. Third I started exercising.</p>
<p>Obviously during this time I sometimes regressed but the important thing is just to get back into the routine and keep going.</p>
<p>Also importantly I now try to turn off when I get home, I try my utmost not to do any work from home. Sometimes I need to, and that comes with the territory but again it’s not till the early hours of the morning. On Sundays I will literally not read my email, read news, read any non-fiction, play catchup on any work or even talk about work. I have no issue working 6 days a week, but I need 1 day a week to recharge and work at my optimal level.</p>
<h3 id="conclusion">Conclusion</h3>
<p>Being a programmer its difficult to switch off and stop but you need to. I would suggest making better use of your 9-5 time, use something like the Pomodoro technique or work sessions. Use <a href="/post/being-productive-or-trying-to-be-atleast">materials and tools</a> that scale focus on the important things. Your brain needs to turn off, and your body needs time off. You need just to stop sometimes and think about you.</p>
<hr />
Ruby Koans part 2 - my thoughts thus far2014-07-02T00:00:00+00:00http://deonheyns.com/posts/ruby-koans-part-2-my-thoughts-thus-far<p>I recently <a href="/posts/ruby-koans-how-did-i-only-find-out-about-this-now">discovered</a> how awesome the <a href="http://rubykoans.com/">Ruby Koans</a> are. The last 2 days I have gone through:</p>
<p>###Part 2</p>
<ol>
<li>about_keyword_arguments</li>
<li>about_constants</li>
<li>about_control_statements</li>
<li>about_true_and_false</li>
<li>about_triangle_project</li>
</ol>
<p>###Part 3</p>
<ol>
<li>about_exceptions</li>
<li>about_triangle_project_2</li>
<li>about_iteration</li>
<li>about_blocks</li>
<li>about_sandwich_code</li>
<li>about_scoring_project</li>
</ol>
<p>I have already mentioned <a href="/posts/the-ruby-way-what-does-it-mean">how much I like Ruby</a> thus far, and these past few Koans have just opened up my eyes to how easy and expressive <a href="https://www.ruby-lang.org/en/">Ruby</a> is whilst still not requiring lines and lines of code.</p>
<p>The about_blocks section was especially interesting to me the lambda declaration was pretty neat</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
</pre></td><td class="code"><pre><span class="n">silence</span> <span class="o">=</span> <span class="nb">lambda</span> <span class="p">{</span> <span class="o">|</span><span class="n">n</span><span class="o">|</span> <span class="n">n</span> <span class="o">+</span> <span class="mi">1</span> <span class="p">}</span></pre></td></tr></tbody></table></code></pre></figure>
<p>The syntax for the find_all, map, collect and select are very succinct, and I certainly can see why many people new to programming pick Ruby because its so easy to read and grok. Just check this</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="code"><pre><span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">].</span><span class="nf">select</span> <span class="p">{</span> <span class="o">|</span><span class="n">item</span><span class="o">|</span> <span class="p">(</span><span class="n">item</span> <span class="o">%</span> <span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">}</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">].</span><span class="nf">collect</span> <span class="p">{</span> <span class="o">|</span><span class="n">item</span><span class="o">|</span> <span class="p">(</span><span class="n">item</span> <span class="o">%</span> <span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">}</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">].</span><span class="nf">find_all</span> <span class="p">{</span> <span class="o">|</span><span class="n">item</span><span class="o">|</span> <span class="p">(</span><span class="n">item</span> <span class="o">%</span> <span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">}</span></pre></td></tr></tbody></table></code></pre></figure>
<p>See you can almost read that like any sentence and understand what is happening. I also touched on the Enumerable#inject method, but I still don’t fully understand why many people rave about it. It might just be a case of I don’t grok it yet. So my mission for the rest of the day is to try and understand it better and figure out why many a Rubist loves this method.</p>
<p>I will report back my findings tomorrow, and hopefully I will be able to impart my knowledge (or lack thereof) on the Enumerable#inject method.</p>
<hr />
The Ruby Way - What does it mean?2014-07-01T00:00:00+00:00http://deonheyns.com/posts/the-ruby-way-what-does-it-mean<h3 id="why">Why?</h3>
<p>Two blocks of code, which would you prefer?</p>
<h4 id="my-attempt">My Attempt:</h4>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">triangle</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">)</span>
<span class="k">if</span><span class="p">((</span><span class="n">a</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="o">||</span> <span class="p">(</span><span class="n">b</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">)</span> <span class="o">||</span> <span class="p">(</span><span class="n">c</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">))</span>
<span class="k">raise</span> <span class="no">TriangleError</span>
<span class="k">end</span>
<span class="k">if</span><span class="p">((</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">&lt;</span> <span class="n">c</span><span class="p">)</span> <span class="o">||</span> <span class="p">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">c</span> <span class="o">&lt;</span> <span class="n">b</span><span class="p">)</span> <span class="o">||</span> <span class="p">(</span> <span class="n">b</span> <span class="o">+</span> <span class="n">c</span> <span class="o">&lt;</span> <span class="n">a</span><span class="p">))</span>
<span class="k">raise</span> <span class="no">TriangleError</span>
<span class="k">end</span>
<span class="k">if</span><span class="p">((</span><span class="n">a</span> <span class="o">+</span> <span class="n">c</span> <span class="o">==</span> <span class="n">b</span><span class="p">)</span> <span class="o">||</span> <span class="p">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">==</span> <span class="n">c</span><span class="p">)</span> <span class="o">||</span> <span class="p">(</span><span class="n">b</span> <span class="o">+</span> <span class="n">c</span> <span class="o">==</span> <span class="n">a</span><span class="p">))</span>
<span class="k">raise</span> <span class="no">TriangleError</span>
<span class="k">end</span>
<span class="k">if</span><span class="p">((</span><span class="n">a</span> <span class="o">==</span> <span class="n">b</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">a</span> <span class="o">==</span> <span class="n">c</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="p">(</span><span class="n">b</span> <span class="o">==</span> <span class="n">c</span><span class="p">))</span>
<span class="ss">:equilateral</span>
<span class="k">elsif</span> <span class="p">((</span><span class="n">a</span> <span class="o">==</span> <span class="n">b</span><span class="p">)</span> <span class="o">||</span> <span class="p">(</span><span class="n">a</span> <span class="o">==</span> <span class="n">c</span><span class="p">)</span> <span class="o">||</span> <span class="p">(</span><span class="n">b</span> <span class="o">==</span> <span class="n">c</span><span class="p">))</span>
<span class="ss">:isosceles</span>
<span class="k">else</span>
<span class="ss">:scalene</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<h4 id="the-ruby-way">The Ruby Way?:</h4>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">triangle</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">)</span>
<span class="k">raise</span> <span class="no">TriangleError</span> <span class="k">unless</span> <span class="n">triangleSideLengthsAreValid?</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">)</span>
<span class="k">return</span> <span class="ss">:equilateral</span> <span class="k">if</span> <span class="p">[</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">].</span><span class="nf">uniq</span><span class="p">.</span><span class="nf">length</span> <span class="o">==</span> <span class="mi">1</span>
<span class="k">return</span> <span class="ss">:isosceles</span> <span class="k">if</span> <span class="p">[</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">].</span><span class="nf">uniq</span><span class="p">.</span><span class="nf">length</span> <span class="o">==</span> <span class="mi">2</span>
<span class="k">return</span> <span class="ss">:scalene</span> <span class="k">if</span> <span class="p">[</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">].</span><span class="nf">uniq</span><span class="p">.</span><span class="nf">length</span> <span class="o">==</span> <span class="mi">3</span>
<span class="k">end</span>
<span class="k">def</span> <span class="nf">triangleSideLengthsAreValid?</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">)</span>
<span class="n">ax</span><span class="p">,</span><span class="n">bx</span><span class="p">,</span><span class="n">cx</span> <span class="o">=</span> <span class="p">[</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span><span class="p">].</span><span class="nf">sort</span>
<span class="k">return</span> <span class="p">(</span><span class="n">ax</span><span class="o">+</span><span class="n">bx</span><span class="p">)</span><span class="o">&gt;</span><span class="n">cx</span>
<span class="k">end</span></code></pre></figure>
<p>The first block is my first attempt at the <a href="/posts/ruby-koans-how-did-i-only-find-out-about-this-now/">about_triangle_project_2</a> from the <a href="http://rubykoans.com/">Ruby Koans</a> pretty much the sort of code you would expect to see from the first attempt when learning a new language properly. The second block is something I found after I googled for other solutions. I prefer the second solution over mine since it is much clearer at conveying what is happening. The intent is much easier to grasp than my attempt and its less code.</p>
<h3 id="how">How?</h3>
<p>So what or how do you explain the Ruby Way and how do you start thinking in the Ruby Way? Those are questions I don’t have an answer to…yet! <a href="http://www.infoq.com/articles/what-is-the-ruby-way">Hal Fulton</a> said</p>
<blockquote>
<p>On the one hand, it means a method or technique, but it can also mean a road or path. Obviously these two meanings are interrelated, and I think when I say, “the Ruby Way,” I mean both of them.</p>
</blockquote>
<p>So to me the interesting point is “the method or technique”. I looked for some more examples today and came across this code that swaps two values</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">y</span><span class="p">,</span> <span class="n">x</span></code></pre></figure>
<p>Really!?!? Is that’s all it takes to swap values.</p>
<p><img src="http://deonheyns.com/images/mind_blown.gif" alt="Mind Blown" /></p>
<p>Look at this</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">find_by_year_month</span><span class="p">(</span><span class="n">year</span><span class="p">,</span> <span class="n">month</span><span class="p">)</span>
<span class="n">requested_date</span> <span class="o">=</span> <span class="no">Date</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">year</span><span class="p">,</span> <span class="n">month</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">from</span> <span class="o">=</span> <span class="n">requested_date</span> <span class="o">-</span> <span class="mi">1</span>
<span class="n">to</span> <span class="o">=</span> <span class="n">requested_date</span> <span class="o">&gt;&gt;</span> <span class="mi">1</span>
<span class="n">engagements</span> <span class="o">=</span> <span class="n">find</span><span class="p">(</span><span class="ss">:all</span><span class="p">,</span> <span class="ss">:conditions</span> <span class="o">=&gt;</span> <span class="p">[</span><span class="s2">"start BETWEEN ? and ?"</span><span class="p">,</span> <span class="n">from</span><span class="p">,</span> <span class="n">to</span><span class="p">],</span>
<span class="ss">:order</span> <span class="o">=&gt;</span> <span class="ss">:start</span><span class="p">)</span>
<span class="n">engagements</span><span class="p">.</span><span class="nf">group_by</span> <span class="k">do</span> <span class="o">|</span><span class="n">engagement</span><span class="o">|</span>
<span class="n">engagement</span><span class="p">.</span><span class="nf">start</span><span class="p">.</span><span class="nf">strftime</span><span class="p">(</span><span class="s2">"%Y%m%d"</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span></code></pre></figure>
<p>compared to this</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">find_by_year_month</span><span class="p">(</span><span class="n">year</span><span class="p">,</span> <span class="n">month</span><span class="p">)</span>
<span class="n">date</span> <span class="o">=</span> <span class="no">Time</span><span class="p">.</span><span class="nf">gm</span> <span class="n">year</span><span class="p">,</span> <span class="n">month</span>
<span class="n">engagements</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">all</span> <span class="o">=</span> <span class="n">find</span><span class="p">(</span><span class="ss">:all</span><span class="p">,</span> <span class="ss">:conditions</span> <span class="o">=&gt;</span> <span class="p">[</span><span class="s2">"start &gt;= ? and start &lt;= ?"</span><span class="p">,</span> <span class="n">date</span><span class="p">.</span><span class="nf">last_month</span><span class="p">.</span><span class="nf">end_of_month</span><span class="p">,</span> <span class="n">date</span><span class="p">.</span><span class="nf">next_month</span><span class="p">.</span><span class="nf">beginning_of_month</span><span class="p">],</span> <span class="ss">:order</span> <span class="o">=&gt;</span> <span class="ss">:start</span><span class="p">)</span>
<span class="n">all</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">e</span><span class="o">|</span>
<span class="n">key</span> <span class="o">=</span> <span class="n">e</span><span class="p">.</span><span class="nf">start</span><span class="p">.</span><span class="nf">strftime</span><span class="p">(</span><span class="s1">'%Y%m%d'</span><span class="p">)</span>
<span class="n">engagements</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span> <span class="k">unless</span> <span class="n">engagements</span><span class="p">.</span><span class="nf">has_key?</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="n">engagements</span><span class="p">[</span><span class="n">key</span><span class="p">].</span><span class="nf">push</span> <span class="n">e</span>
<span class="k">end</span>
<span class="n">engagements</span>
<span class="k">end</span></code></pre></figure>
<p>I know that I would prefer the first code block over the second. Also, while searching I came across the <a href="https://github.com/styleguide/ruby">GitHub Style Guide</a> for Ruby, that has some nice advice on coding style that I will often be revisiting.</p>
<h3 id="conclusion">Conclusion</h3>
<p>I am still figuring out the how. To me I don’t believe that thinking or writing code in the Ruby Way will happen overnight. I have read a few suggestions of blogs and <a href="http://mislav.uniqpath.com/poignant-guide/">books</a> that will help you to start doing things in the Ruby Way but clearly this is a skill that needs to be practiced to master. All I can say is that this language is very impressive and around every corner has more and more sweet features</p>
<hr />
Ruby Koans how did I only find out about this now?2014-06-30T00:00:00+00:00http://deonheyns.com/posts/ruby-koans-how-did-i-only-find-out-about-this-now<h3 id="why">Why?</h3>
<p>I’m <a href="/posts/rails-here-is-my-plan-to-learn-ruby">learning Ruby</a> part of my <a href="/posts/how-to-set-your-goals-the-right-way">plan</a> is to go through the <a href="http://rubykoans.com/">Ruby Koans</a>. I started yesterday (2014-07-29), and tonight was part 2 of 5.</p>
<p>The Ruby Koans site states:</p>
<blockquote>
<p>The Koans walk you along the path to enlightenment in order to learn Ruby. The goal is to learn the Ruby language, syntax, structure, and some common functions and libraries. We also teach you culture. Testing is not just something we pay lip service to, but something we live. It is essential in your quest to learn and do great things in the language.</p>
</blockquote>
<h3 id="how">How?</h3>
<p>The Koans are 33 different lessons covering various topics, but I won’t be doing the JRuby Koan so I will only be doing 32. The first evening I started I done the first 10. You can either download the Koans or you can do them online. My choice is to do them online, but my process (as with most coding tutorials or books) is to copy the code to my IDE and do the lessons locally. I have broken the Koans up over 5 parts that I will do over 5 days.</p>
<p>###Part 1</p>
<ol>
<li>about_asserts</li>
<li>about_nil</li>
<li>about_objects</li>
<li>about_arrays</li>
<li>about_array_assignment</li>
<li>about_hashes</li>
<li>about_strings</li>
<li>about_symbols</li>
<li>about_regular_expressions</li>
<li>about_methods</li>
</ol>
<p>###Part 2</p>
<ol>
<li>about_keyword_arguments</li>
<li>about_constants</li>
<li>about_control_statements</li>
<li>about_true_and_false</li>
<li>about_triangle_project</li>
</ol>
<p>###Part 3</p>
<ol>
<li>about_exceptions</li>
<li>about_triangle_project_2</li>
<li>about_iteration</li>
<li>about_blocks</li>
<li>about_sandwich_code</li>
<li>about_scoring_project</li>
</ol>
<p>###Part 4</p>
<ol>
<li>about_classes</li>
<li>about_open_classes</li>
<li>about_dice_project</li>
<li>about_inheritance</li>
<li>about_modules</li>
<li>about_scope</li>
</ol>
<p>###Part 5</p>
<ol>
<li>about_class_methods</li>
<li>about_message_passing</li>
<li>about_proxy_object_project</li>
<li>about_to_str</li>
<li>about_extra_credit</li>
</ol>
<p>These are pretty cool as each Koan builds up your knowledge as you go. The language and the syntax are much less verbose than C#, and I am pretty happy about that, who doesn’t want to write less code to get the same amount of work done?</p>
<p>Another thing I really like is how you are taught through Unit Testing, so not only are you learning <a href="https://www.ruby-lang.org/en/">Ruby</a> you are also learning how to write Unit Tests and to do it using TDD.</p>
<h3 id="conclusion">Conclusion</h3>
<p>So far the <a href="http://rubykoans.com/">Ruby Koans</a> are pretty fantastic, and I recommend them to anyone. Granted that this isn’t my first experience with <a href="https://www.ruby-lang.org/en/">Ruby</a> but this is the first time I am really trying to become more proficient in the language. The Koans have already enlightened me, and I will keep doing them and report back my progress tomorrow.</p>
<hr />
Rails - Here is my plan to learn Ruby2014-06-29T00:00:00+00:00http://deonheyns.com/posts/rails-here-is-my-plan-to-learn-ruby<h3 id="why">Why?</h3>
<p>I am on a mission, <a href="/posts/rails-my-plan-to-get-a-pull-request-accepted">I want to contribute to Rails</a>. However I need to become familiar with the language <a href="http://rubyonrails.org/">Rails</a> is written in. Unless you have been living under a rock for the last 9 years you will know that is <a href="https://www.ruby-lang.org/en/">Ruby</a>.</p>
<p>So I done the <a href="/posts/haiku-friday-my-week-with-rails">Rails Blog Tutorial</a> and while I found it interesting I am definitely going to need a deeper understanding of <a href="http://pragprog.com/book/ruby4/programming-ruby-1-9-2-0">Ruby</a> and how it works. So I am going to bake into my overall plan. By October 31 2014 I plan to be proficient enough in <a href="https://www.ruby-lang.org/en/">Ruby</a> to make a meaningful contribution to any <a href="https://www.ruby-lang.org/en/">Ruby</a> project.</p>
<p>I have been writing on how to set your <a href="/posts/how-to-set-your-goals-the-right-way">goals</a> the right way and how to set <a href="/posts/setting-proper-deadlines">deadlines</a>. So here are mine. I think I have a good plan might need so tweaking and I need to set the metrics but I think this is achievable.</p>
<h3 id="how">How?</h3>
<ol>
<li>
<p>Complete the <a href="http://koans.heroku.com/">Ruby Koans</a> July 4th 2014</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; 10 Koans by June 29</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; 11 Koans by July 2</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; 11 Koans by July 4</p>
</li>
<li>
<p>Read <a href="http://mislav.uniqpath.com/poignant-guide/">Why’s (poignant) guide to Ruby</a> by August 27 2014</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; Read Chapter 1 by July 11</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; Read Chapter 2 by July 18</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; Read Chapter 3 by July 25</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; Read Chapter 4 by August 1</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; Read Chapter 5 by August 8</p>
<p>&lt;input type=checkbox disabled=”disabled” checked/&gt; Read Chapter 6 by August 15</p>
</li>
<li>
<p>Read <a href="http://pragprog.com/book/ruby4/programming-ruby-1-9-2-0">Programming Ruby 1.9 &amp; 2.0 (4th edition): The Pragmatic Programmers’ Guide</a> by October 31 2014</p>
<p>&lt;input type=checkbox disabled=”disabled”/&gt; Read Facets of Ruby by September 30</p>
<p>&lt;input type=checkbox disabled=”disabled”/&gt; Ruby in Its Setting by October 17</p>
<p>&lt;input type=checkbox disabled=”disabled”/&gt; Ruby Crystallized by October 31</p>
</li>
</ol>
<h3 id="conclusion">Conclusion</h3>
<p>A <a href="/posts/how-to-set-your-goals-the-right-way">goal</a> needs to be set correctly with achievable <a href="/posts/setting-proper-deadlines">deadlines</a>. My plan is set and now its time to put it in motion. I hope to share my learning with you and hope by the end of this to be a <a href="http://rubyonrails.org/">Rails</a> contributor.</p>
<hr />
Tracking your goals2014-06-28T00:00:00+00:00http://deonheyns.com/posts/tracking-your-goals<h3 id="why">Why?</h3>
<p>How will you know what whether or not you will hit your <a href="/posts/setting-proper-deadlines">deadline</a>? How can you create some accountability without having a “boss” look over your shoulder?</p>
<p>If you start tracking your <a href="/posts/how-to-set-your-goals-the-right-way">goals</a>, you will know how far away you are to reaching your goal, how much work is left to do to hit your goal and will you make your deadline exactly if you have hit your <a href="/posts/setting-proper-deadlines">deadline</a>. You will now have a way to “know where you are” which is invaluable in software engineering and life in general.</p>
<h3 id="how">How?</h3>
<p>You will need to find a quantifiable metric to measure your progress that’s the hardest part. What to measure and how to measure? Take some thought. Let’s say you wanted to measure a software project you could use feature implementation or story delivery as your milestones to track your goal of delivering a product. If it was something personal like losing weight, you might use your weekly weigh-in or the inches around your waist as your milestone. For your fitness you could track mileage and the number of consecutive minutes you can run.</p>
<p>Remember milestones are <a href="/posts/how-to-set-your-goals-the-right-way">goals</a> so use the same techniques you used to set your goals to set your mini-goals or milestones.</p>
<p>Here is a more concrete example on the 1st of January 2014 I weighed 214 pounds, I was overweight, always tired and super stressed. I decided I wanted to lose the weight. Knowing that I couldn’t just starve myself and that diets are usually not sustainable over the longterm I knew I had to adopt a healthy lifestyle my plan was simple:</p>
<blockquote>
<p>Weigh 175 pounds by the end of the 1st of June 2014</p>
</blockquote>
<p>How would I achieve this?</p>
<ul>
<li>Complete the couch to 5k plan by 28th of February 2014</li>
<li>Do morning and evening yoga every Monday, Tuesday, Wednesday, Thursday, Sunday</li>
<li>Replace my normal breakfast with a smoothie and eat some fruit for lunch</li>
<li>Be in bed at the latest 10pm every night and wake up at 6am</li>
</ul>
<p>My milestones</p>
<ul>
<li>Run 5k by 28th of February without walking</li>
<li>Weigh myself each Friday to make sure that I was losing enough weight to reach my goal</li>
<li>Each Monday I make sure I had 10k steps per day for the previous week</li>
<li>Every morning I check the time I went to bed and woke up using my Fitbit</li>
</ul>
<p>I tried to be as clear as possible as to what my milestones were and made sure to check them each week.</p>
<h3 id="conclusion">Conclusion</h3>
<p>The vaguer your goal, the more difficult it is to come up with milestones and thus it will be harder to track. It will be impossible to measure your goal until you refine and define what your goal is. As soon as you start seeing a metric or milestone within your goal you know you have something to work with and work towards achieving.</p>
<p>I am using this exact approach in formulating my plan to reach my goal of contributing to Rails, and I will post it in the coming week for all to see.</p>
<hr />
Haiku Friday - My week with Rails!2014-06-27T00:00:00+00:00http://deonheyns.com/posts/haiku-friday-my-week-with-rails<p>##Rails Blog Tutorial</p>
<p><img src="http://deonheyns.com/images/rails_tutorial.jpg" alt="Rails Tutorial" /></p>
<p>##Released on 13 December 2005</p>
<p><img src="http://deonheyns.com/images/rails_created.jpg" alt="Released in 13 December 2005" /></p>
<p>##Still Causing hair loss</p>
<p><img src="http://deonheyns.com/images/rails_hairloss.jpg" alt="Still Causing hair loss " /></p>
<hr />
Setting proper deadlines2014-06-26T00:00:00+00:00http://deonheyns.com/posts/setting-proper-deadlines<h3 id="why">Why?</h3>
<p>Can you really call a goal a goal when it has no deadline? I don’t believe so. So what makes a good deadline or how should you set deadlines. Let’s first understand why setting a proper deadline is a key element in setting a good goal.</p>
<p>Deadlines cause pressure and this is a good thing when you are trying to achieve something. A good balanced deadline will ensure that you are pressurized to achieve the deadline, will help prevent procrastination, and when it is far enough away, it will allow you to produce quality work.</p>
<p>If you set a deadline and it’s too close, it will cause you stress and hamper your creative ability, you will become so focused on getting it done that you won’t have the time to stop, look at the problem and design an elegant solution. You need breathing space you need the ability to be able to walk away from the problem or task and comeback refreshed and relaxed to produce some quality work.</p>
<p>However, if you set a deadline too far in the future that could spell disaster. You will have more time to procrastinate. The urgency to get the task done wouldn’t be there and each day you would put it off to the next until it was a day before the deadline and then suddenly you would realize you made a massive mistake.</p>
<h3 id="how">How?</h3>
<p>So let’s get down to business how do you set deadlines and have confidence in them? Since I am a Software Engineer I use <a href="https://www.kennethnorton.com/essays/leading-cross-functional-teams.html">Ken Norton’s</a> rule of thumb for estimates and ask myself the following questions and answer them as honestly as I can:</p>
<p>####Likely estimate (L):
“How long do I think this will take?”</p>
<p>####Pessimistic estimate (P):
“What is the longest this will take me accounting for unforeseen roadblocks?”</p>
<p>####Optimistic estimate (0):
“What’s the least amount of time required if everything goes well?”</p>
<p>I then plug my answers into this equation</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>O + (L + 4) + P
---------------
6
</code></pre></div></div>
<p>I then use this as my deadline for a given task. This technique has served me well thus far, and this is the same equation I am using to create my deadline to contributing to open source projects.</p>
<h3 id="conclusion">Conclusion</h3>
<p>For me, deadlines always cause stress, even using this technique I still feel anxious getting closer to my deadlines. However, I do feel a lot more confident with my deadlines and estimates in general. Don’t let your deadlines suck up all your productive energy. Create your goals and make balanced deadlines that you can stick to and feel good about.</p>
<hr />
How to set your goals the right way2014-06-25T00:00:00+00:00http://deonheyns.com/posts/how-to-set-your-goals-the-right-way<h3 id="why">Why?</h3>
<p>In an earlier post, you would have seen I have a plan to get a pull request accepted to Rails. I have played around with RoR and written some fairly basic Ruby nothing that I would call production grade. So how do I intend on getting to the level where I am confident in my skills?</p>
<p>I need a plan and I need to set my goals correctly as failing to do so is planning to fail. What you need to remember is that productivity and success is not an accident it doesn’t just happen its always the result of</p>
<ul>
<li>A genuine commitment to producing excellence</li>
<li>Planning and not just any planning excellent and thorough planning</li>
<li>Perseverance and focus</li>
</ul>
<h3 id="how">How?</h3>
<p>So how do you set or define goals? Here are the guidelines I use and will be using in formulating my plan in making my open source contribution</p>
<ul>
<li>The goal must be written in detail</li>
<li>The goal must be clear</li>
<li>The goal must be specific</li>
<li>A goal must have a milestone</li>
<li>The goal must include a deadline</li>
<li>The goal must not contradict any of my other goals</li>
<li>The goal must be accompanied by a plan to achieve it</li>
<li>The goal must be measurable, and you need to include metrics</li>
<li>Most importantly you must believe deep down that you can achieve it</li>
</ul>
<h3 id="conclusion">Conclusion</h3>
<p>There are <a href="http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&amp;field-keywords=goal+setting&amp;rh=n%3A283155%2Ck%3Agoal+setting">thousands of books on goal setting</a> I am by no means an expert. So far this is what is working for me quite successfully, in the future as I iterate I am pretty sure things will change.</p>
<hr />
ActiveModel::ForbiddenAttributesError in BlogPostsController#comments2014-06-24T00:00:00+00:00http://deonheyns.com/posts/activeModel-forbiddenattributeserror-in-blogpostscontroller<h3 id="wtf">WTF</h3>
<p>So today while going through the legendary “Create a Blog with Rails” tutorial I got this fantastic error message:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
</pre></td><td class="code"><pre><span class="no">ActiveModel</span><span class="o">::</span><span class="no">ForbiddenAttributesError</span></pre></td></tr></tbody></table></code></pre></figure>
<p>Okay, so some or other attributes are forbidden well thanks that is informative. So this helped a bit though at least I knew what line was giving me an error.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="code"><pre><span class="c1"># POST /comment
</span>
<span class="k">def</span> <span class="nf">comment</span>
<span class="vi">@comment</span> <span class="o">=</span> <span class="no">Comment</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:comment</span><span class="p">])</span> <span class="c1">#Error is here</span></pre></td></tr></tbody></table></code></pre></figure>
<p><img src="http://deonheyns.com/images/ActiveModelForbiddenAttributesError.jpg" alt="ActiveModel::ForbiddenAttributesError in BlogPostsController#comments" /></p>
<p>So I obviously googled this and got to this <a href="http://stackoverflow.com/a/17335871">StackOverflow answer</a></p>
<blockquote>
<p>I guess you are using Rails 4. If so, the needed parameters must be marked as required.</p>
</blockquote>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
4
</pre></td><td class="code"><pre>
<span class="k">def</span> <span class="nf">user_params</span>
<span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:user</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:username</span><span class="p">,</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">:password</span><span class="p">,</span> <span class="ss">:salt</span><span class="p">,</span> <span class="ss">:encrypted_password</span><span class="p">)</span>
<span class="k">end</span></pre></td></tr></tbody></table></code></pre></figure>
<p>So all I needed was to add this</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="code"><pre><span class="k">def</span> <span class="nf">comment_params</span>
<span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:comment</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:email</span><span class="p">,</span> <span class="ss">:comment</span><span class="p">,</span> <span class="ss">:blog_post_id</span><span class="p">)</span>
<span class="k">end</span></pre></td></tr></tbody></table></code></pre></figure>
<p>and change my comment method to</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><table class="rouge-table"><tbody><tr><td class="gutter gl"><pre class="lineno">1
2
3
</pre></td><td class="code"><pre><span class="c1"># POST /comment
</span>
<span class="k">def</span> <span class="nf">comment</span>
<span class="vi">@comment</span> <span class="o">=</span> <span class="no">Comment</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">comment_params</span><span class="p">)</span></pre></td></tr></tbody></table></code></pre></figure>
<p>I struggled with this for a while and looking back I feel like an idiot that the fix was so easy o_O.</p>
<hr />
How to encourage collaboration amongst programmers2014-06-23T00:00:00+00:00http://deonheyns.com/posts/how-to-encourage-collaboration-among-programmers<h3 id="why">Why</h3>
<p>Programmers are problem solvers and are thus so busy that they often never make the time or get a chance to share their knowledge. At times, some programmers just don’t want to share their knowledge as they are afraid they will lose the edge on their peers. And at other times its just so damn hard to share knowledge effectively that programmers become silos of knowledge. Some other reasons might be the fear of not knowing the answer, more work or the fear of being wrong.</p>
<h3 id="how">How?</h3>
<ol>
<li>Encourage people to share, have lunch ‘n learns, commend those who you see sharing their knowledge. Collaboration requires that the parties involved share goals.</li>
<li>Find the simplest way to collaborate and share this information. I have found that a medium that is easily accessible and search-able has the best results. Nothing is more frustrating than trying to find something you know exists but is very difficult to find. I don’t believe a shared drive with hundreds of documents is the best solution.</li>
<li>Take the first step. If you ask a colleague for help then document the details and outcome on the medium where you share this information.</li>
<li>Make this repository of information editable by anyone in the team. Things change; processes and procedures evolve, therefore, your documentation should too.</li>
</ol>
<h3 id="conclusion">Conclusion</h3>
<p>Collaboration is difficult but not impossible take small steps by getting a <a href="http://en.wikipedia.org/wiki/Wiki">wiki</a> setup or even a <a href="https://sites.google.com">Google site</a>. I have found this small steps to be effective but YMMV.</p>
<hr />
Rails - my plan to get a pull request accepted2014-06-22T00:00:00+00:00http://deonheyns.com/posts/rails-my-plan-to-get-a-pull-request-accepted<h3 id="why">Why?</h3>
<p>I have spent most of my career on the Microsoft Stack, and I would like to contribute to the <a href="http://rubyonrails.org/">Ruby on Rails</a> project. Like any good developer, I learn or up-skill on different languages. I am fairly comfortable in JavaScript and so so with Python however I would like to be much more proficient in Ruby and Scala.</p>
<h3 id="how">How?</h3>
<p>My plan is as follows:</p>
<p>Find an open source Ruby project that has documentation
Read the documentation and see if there is any way I can update or better the documentation
Update the docs and send a pull request
Are you noticing that none of this isn’t toward Rails? Well, the way I see it is it will be better to dip my toes in on another project before I go for the big one. Its like running a marathon, you first do 5Ks, then a 10K, thereafter 10 miles, then a half marathon and finally a marathon. It is pretty scary sending a pull request to a large project like Rails so I would rather train before I go in all guns blazing.</p>
<p>So next my plan is to go through the Rails issues on GitHub and pick one. I will then fix this and send a PR for my fix. Hopefully, I can get some constructive feedback on my code, and it gets approved with little issues. constructive feedback on my code and it gets approved with little issues.</p>
<h3 id="conclusion">Conclusion</h3>
<p>So this is my plan maybe its the right one maybe its the wrong one who knows? I will let you know how it goes.</p>
<hr />
Being productive or trying to be at least2014-06-21T00:00:00+00:00http://deonheyns.com/posts/being-productive-or-trying-to-be-atleast<h3 id="why-do-you-want-to-be-productive">Why do you want to be productive?</h3>
<p>You can never get time back. Every minute that you procrastinate is another minute gone of your life. Truth is you are dying and every time the second-hand ticks is a second closer to your time here on Earth being up.</p>
<p>Clearly you need to make every second count. We all have had that voice in our heads at the end of the day saying we could have and should have done more. So how can you get rid of this voice? How can you make sure that at the end of the day you feel fulfilled? Well, here is my little tip and hopefully it can help you.</p>
<h3 id="tips">Tips</h3>
<p>I have read a few blog posts where people blast todo lists, and there are others that love them. Honestly todos are for some and not for others. Just like some people like carrots and others don’t. I have a little system I use that, thus far, is helping me get the most important things done more importantly this scales!</p>
<p>Here is what you need</p>
<ul>
<li>A notebook</li>
<li>Pen</li>
<li>Five minutes of quite time</li>
</ul>
<p></p>
<ol>
<li>On your notebook write today’s date.</li>
<li>Write all the tasks you need to do for that day</li>
<li>Rank all your items in terms of importance 1 = Must Do, 2 = Should do, 3 = Leave for later, 4 = Delegate and 5 = Eliminate</li>
<li>As you get items done cross them off</li>
<li>For each item, you don’t complete draw an arrow next to them, and when you do your planning, tomorrow put them on your list and rank</li>
</ol>
<h3 id="conclusion">Conclusion</h3>
<p>That is my simple method. What I have found is any system that is simple will be easier to use and there is less chance of getting frustrated</p>
<hr />