Skip to content

I am a lazy dev – I build scripts to write my code!

Lazy…or productive?

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. 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 Fakergem library returns. I wanted to use Express 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.

route_name = File.basename(doc, '.md')
properties = File.open(doc, 'r', &:read).scan(/^Faker\.(\w+)\.(\w+)/).map {|match|
  "#{match[1]}: Faker.#{match[0]}.#{match[1]}()"
}.uniq

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!

File.open("./routes/#{route_name}.js", 'w') do |f|
  f.puts TEMPLATE
    .gsub(/\{route_name\}/, route_name)
    .gsub(/\{properties\}/, properties.join(",\n    "));
end

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.

puts "app.use(require('./routes/#{route_name}'));"

 

So this was how I used Ruby to help me when writing my API. Lazy??? Nah, I prefer the word efficient!

Published inexpressjsnodejsRuby

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *