Crystal Lang – Converting Decimal to Hex

I’ve been writing crystal again and started working on a new api adaption in crystal. One thing I’ve noticed is there’s no actual library to check details about images currently, so I started to play around and figure out how I could do this in pure crystal. I’m not the brightest tool in the shed, but I’m good at using my resource skills to solve a problem.

First off, I needed to figure out how to check if an image is a valid type being submitted to the api that I’m writing for my api adaption. So I knew I needed to deal with the raw bytecode directly, but I didn’t know how I’d actually use it. So after a few minutes of googling I found out I could use common file signatures to figure out if an image is a certain image type based on HEX data. Now there’s this site that documented a list of common file signatures and so I went from there.

I was trying to figure out how to convert a decimal from the byte[] array to the hex data I needed and I couldn’t figure out how to do it using crystal’s standard library directly. So I did what any programmer would do and opened up stackoverflow. I found an example written in python and I used that example and converted it into crystal code.

And everything worked out. So I’m like cool, this is perfect, now I can use that signature data and compare hex values to check for valid image types as a base. So I post on the channel (dev’s talk about and answer questions regarding crystal) asking if something similar to this would be added to the stdlib and one of the users (not sure if he’s a main dev) hit me with the ‘oh you can do this’ and gave me this example:


I’m like, seriously? I literally cut my 10 line python adaption to 1 line. This isn’t even documented or it isn’t documented well, so how would I have known about this feature. So now I’m writing a blog on how easy it is to convert a decimal to hex value using crystal. Man I love this language.

Crystal Language – Passing a closure (block) as a method/function argument.

So I’ve been working with crystal for a few weeks now and I’m still learning a lot of things about the language. One of those things that I had to figure out was passing a closure as a method or function argument.

Lets talk about PHP

Just to give you some background, I’m a php developer and we have a few primary frameworks out there and some of which you may have heard such as: Symfony, Zend Framework, CakePHP, Slim, Silex, etc… just to name a few. Now there’s a handful of frameworks and routers for crystal already, but they’re more catered to how you’d do things the ruby way and I’m not really comfortable with that style of coding. Not that there’s anything is wrong with that style of code, I just prefer to get things back to how I had things setup previously in my php workflow. Which brings me to how Slim Framework 3 handles routes. For example:

Here slimframework has this way to group routes in such a way that makes adding a ton of routes a bit easier when say we want to go back and change a base path. For instance, if the admin panel path changed we can wrap all the admin routes in a group then edit just the group without having to edit all our routes and call it a day.

Now a way to accomplish this in php is to pass a closure as a parameter and then bind the class to that closure where we can access all the class methods inside the current instance. Now the way you’d handle the grouping is by setting the route prefix (or group) inside the actual group method when we define it, followed by calling the closure, then cleaning up the prefix data so when we end the group method’s definition it doesn’t mess up other routes that aren’t set inside a group.

Now one problem most people would run into is how would one continuously call the group method for sub groups. Well the easiest approach is to have an array of string data and then append the group route to the array, call our closure, then pop off the last group route from the array. What this accomplishes is it allows us to continously add as many sub groups as we want because we’re constantly passing the current instance down the chain.

Accomplishing the same thing in Crystal Lang

So in order to accomplish the same thing in crystal language I needed to first figure out how to pass closures to methods as a parameter. Which actually turned out to be a bit easier than I expected despite the documentations being a bit confusing.

So first off when defining a block parameter you must use the &name syntax. Calling &name as a parameter tells the method or function that we’re going to be passing a block/closure. That’s the most basic example of a block in crystal. Which takes no parameters and returns no value. Inside the function or method that we define we would then need to call the call() definition on the block in order to execute it. You’d treat it like a class definition basically. So if you define any parameters you’d pass those parameters to the call definition in order to access that data inside the closure that you’re passing. Here’s that basic example of a no parameter block:

Simple right? Now how do we pass an empty closure to the example definition? Well you’d use the &-> {} syntax. It’s a definition short hand at it’s most basic form. So at first sight it doesn’t really look too appealing and probably a bit confusing. Now according to the documentation we can also use the do ... end syntax. Which is a lot cleaner, but the difference is the first shorthand syntax requires you to define the function argument types (if any) whilst the do ... end syntax just requires the names for parameters to access that data. Here’s an example of doing just that.

One thing I forgot to mention in my above example is how to define block parameters. The first example shows you the very bare bones example of passing an empty closure to a function. Now if you look at example2 above. You’ll notice a colon with a type after the closure/block name followed with a dart or arrow, which is required in order for it to work, and since there is no return type following the dart operator the return type is void. Although you can use an underscore to return “any” type.

Putting it all together

Now putting it all together to copy the slim framework 3 group routes system that I want to accomplish for my website.

(Note this is bare bones excluding controller#action’s code and what not. I basically just wanted to share with you how to chain the group calls together in a fashionable manner.)

Enjoy and I hope you learned something today 🙂

Understanding Fields (Backing Fields) & Properties in C#

Alright, so I’m learning C# in detail now and somehow I’ve never really put into thought why something like a backing field was necessary or what a (backing) field really was until I was experimenting with Kotlin (a JVM language) for android development. The error occurred because Kotlin’s classes don’t allow backing fields and I was writing kotlin like java at the time which gave me that error. So now when getting back into C# I was trying to understand exactly what a backing field was and to my findings it’s a little simpler than what I was actually expecting. For me when I’m learning a new language I usually just accepted things as they are and a lot of newer programmers are like that. Rather than me understand why something works like it does and all the intricacies that comes with that language feature.

C# and I believe Java both have fields and properties. At first glance you would think they are the same. So what is a field? According to Microsoft’s definition, a field is a variable of any type that is declared directly in a class or struct. Now that’s a pretty generic description, it’s just a class variable right? Yeah, that’s exactly what a field is, it’s a variable that is defined and used within your classes.

Well then what the hell is a property? A property is just a field, usually with public visibility, with a fancy mechanism for accessing and writing data to a private variable. Why would I need that? Usually you don’t, but there are cool ways to introduce data conversions without using class methods to do so. So for example, say you have a database which stores unix timestamps right? Say you wanted to check what time it was an hour ago without modifying the timestamp or using class methods? This is when backing fields come into play. A backing field is just a field that is used by properties when you want to modify or use that private field data.  In other words, a property is just a reference to another private variable.  So to get back to our example:

So above we have a post object which takes a timestamp as a constructor parameter.  Our post object has a read only property, HourAgo, which gets the current timestamp and subtracts an hour from that timestamp.

Now you may or may not need backing fields.  You may just want automatic properties which generate backing fields for you and C#6 has you covered by simply calling:

public type property { get; set; } = value;

Which is pretty cool as well.  Some might say, well couldn’t I just create a class method?  Well yeah you could but properties can be a bit more powerful when it comes to dealing with data values especially with the set accessor property. Say using our example that we wanted to directly update the timestamp by passing a single digit which represents an hour using the HourAgo variable that subtracts exactly an hour from the current timestamp? Well we can modify our HourAgo variable and add a set property accessor to do just that:

set { timestamp -= (60 * 60) * value; }

Now if we called post.HourAgo = 1; it would subtract exactly 1 hour from the current timestamp.  Now picture how powerful this would be if we created say a music player with a feature like fast forward or rewind. We could create properties rather than using class methods which is extremely powerful.

Hopefully we should understand how Properties & Fields work and how they work together.


IdiotCoder is a new programming development/learning blog.  I’ve currently been a PHP developer for about 10 years now and I’ve decided that in order for me to grow as a programmer I need to move on from web development and go full forced into software and game development.  Web development has always been a passion and career of mine, but I’ve always wanted to be a game developer ever since I got into programming.  There’s a lot about programming that I don’t understand in languages such as C/C++, C# and Java, but there’s a lot I’ve tinkered with over the years while experimenting with those languages and others such as Kotlin, Nim, Go, Crystal and probably many more that have made me a better PHP developer.

I’ve learned that learning other languages can teach you how to think outside the box because each language has many different approaches and tools as well as limitations that other languages might not have like being functional only language or being class only language. You have to respect those limitations of what you have to solve those problems.

With that said you’ll see a lot of “no shit sherlock” posts which could be as simple as a few lines or longer thought out posts discussing or describing a finding while learning a language or parts of many languages.  I’m going to focus my efforts on posting things I had a hard time researching and finding a direct answer to so others can find that answer in a direct manner rather than a lot of articles beating around the bush on how something works.  That’s the true goal of this blog.  A learning experience for me and a reference for newer developers going through the same thing.