DEV Community

Cover image for Building a CLI with an API✨
Cathy Diaz
Cathy Diaz

Posted on

Building a CLI with an API✨

Building a CLI from scratch has been a headache and a blessing at the same time. I now understand more about coding and feel 100% more comfortable with continuing on with this journey. But let me tell you, it didn’t come easy. I spent days working on this project, thinking, how will I ever graduate in five months if I can’t even understand the beginning concepts, but as the time passed and I went over the material more and more, it all became easier. I would find myself saying “ahhhhh” more often. Like a 💡 went on and it all finally made sense.

Something I originally had trouble with was metaprogramming. In Wikipedia, this is defined as a programming technique in which computer programs have the ability to treat other programs as their data. In other words, metaprogramming is the practice of writing code that writes code for us. Making it easier to work with our programs.

For example, if we take a look at the codes below, we can see the difference between not using and using metaprogramming.

The first image shows how you can create attribute accessors of the data you want your objects to have. You then would initialize with those attribute accessors (creating writer and reader methods) and save the instance. It then shows how you would shovel that instance method into the @@all array.

Alt Text

As you can see below, metaprogramming is used to create easier and more manageable code. Here you can initialize with a hash and iterate over that hash using the #each method to return the key and value of that hash. Then using the method #send to create the key of the attributes named and their value.

Alt Text

Coding this way is better in the long run because I can always return to this section to get the values I am essentially looking for. It makes managing my API easier by creating new objects using that hash.

The last thing I want to mention is that using the concept of separations of concerns has been a life saver. It makes your code so much easier to read and handle. It is having a file that only deals with your CLI, a file that only deals with your API, having a file that only deals with your objects, and having a file that only deals with your execution code and another for your required environment.

You know when you want to execute your code you place that in your run file. And it's the same concept for all your other files.

In order for code to become easier, practice, practice, practice.

Top comments (0)