> ## Content Index
> Fetch the complete content index at: https://www.mrstebo.co.uk/llms.txt
> Use this file to discover other available public pages before exploring further.

# Building scripts to write code! 😵
- URL: https://www.mrstebo.co.uk/building-scripts-to-write-code/
- Published: 2017-04-21T23:00:00.000Z
- Updated: 2023-05-15T23:44:01.000Z
- Author: Steven Atkinson
- Tags: Software Development, Software Engineering, Ruby, NodeJS, Efficiency

Let me get things straight! I ****LOVE** coding! I spend almost ****ALL DAY** coding. But there are some aspects of coding that are a bit tedious!

So today I am going to show you an example of how I try and avoid writing code that shares common behavior.

# Let me provide some context…

I have been writing a port of one of my favorite Ruby gems, [****faker**.](https://github.com/stympy/faker?ref=mrstebo.co.uk) I have been making very good progress with this, and wanted to create an API that can be used for others to show an example of what my library returns. I wanted to use [Express](https://expressjs.com/?ref=mrstebo.co.uk) because it is really easy to get an API up and running when using that library.

# Ruby to the rescue!

In order to prevent myself from writing the same code multiple times, I decided to write a ruby script that’ll just generate the code for me. Of course there are some files that would need a slight change, but at least I could get some generic code written very quickly.

Here is the script!

# Awesome! So what does it do?

So first we have our `TEMPLATE` constant, which is a template of the file I want to create. It simply creates an Express router with a single route that returns a JSON response. I have set up the **{router\_name}* and **{properties}* placeholders that will be replaced by the rest of the script. ****EASY!**

Next I use the `Dir.glob('./node_modules/fakergem/doc/*.md')` function to return all the docs for the fakergem.

Then I create the variables that will be used to replace the placeholders in the template.

The reason I use `uniq` is because there may be multiple examples of a single Faker function.

Now it is time to write the file!

****Wow, so simple!** This will just create a new file with the ****route\_name** extracted from the Faker filename and write the template with the placeholders replaced with the values we extracted from the documentation.

Finally, I wanted to be able to just copy the routes to the file containing my express app. So I just did a simple print out to the console with the the code for requiring the newly created route.

So this was how I used ****Ruby** to help me when writing my API.

Very efficient, right? 😎