diceline-chartmagnifierquestion-marktwitter-whiteTwitter_Logo_Blue

Today I Learned

How to add dynamic images in NuxtJS & VueJS

Let's say you have a simple component in NuxtJS and VueJS, a static image for a blog post.

<template>
  <article class="post__image">
    <img class="image" src="~/assets/images/imageName.jpg" alt="post picture">
  </article>
</template>

Simple enough, right? But you don't want to have the same image for every blog post, so maybe you're trying to add it dynamically, getting the image name through a prop and using Vue's v-bind directive, like so:

<template>
  <article class="post__image">
    <img class="image" :src="`~/assets/images/${imageName}.jpg`" :alt="`${imageName} picture`">
  </article>
</template>

<script>
export default {
  name: 'PostImage',
  props: {
    imageName: String
  },
}
</script>

And then you notice that that doesn't work. But why? The vue syntax is correct, so what's the problem? Well, there's something else at play here.

Behind the scenes, webpack replaces the image path with a module request at build time. That's fine for static images, because their paths are known at build time, but for dynamic images it's a different story, as webpack can't know what their paths will evaluate to at run time, so that won't work.

The solution is to make a module request for the images, so that webpack can work its magic on them before loading them on the page. That's done by using require(...), with the correct image path.

So your images will have to be loaded like this:

<img 
    class="image" 
    :src="require(`~/assets/images/${this.imageName}.jpg`)" 
    :alt="`${imageName} picture`"
>

You could also clean that up a bit, and extract the require part into a computed property, for better readability:

<template>
  <article class="post__image">
    <img class="image" :src="imageSource" :alt="`${imageName} picture`">
  </article>
</template>

<script>
export default {
  name: 'PostWithImage',
  props: {
    imageName: String
  },
  computed: {
    imageSource() {
      return require(`~/assets/images/${this.imageName}.jpg`)
    },
  }
}
</script>

Loop through a list of VueJS components

Ever wondered how you can loop through a list of VueJS components?

Let's say you have an array of components and you want to render them dynamically:

data() {
    return {
        components: ['ComponentOne', 'ComponentTwo', 'ComponentThree']       
    }
}

It's simple. We just need to use vue's dynamic component.

###Let's see how:

<ul>
    <li v-for="component, index in components" :key="index">
        <component :is="component"></component>
    </li>
</ul>

Just make sure to register all the used components where you need them.

How to use chmod to change permissions

For a long time I've been afraid of using the shell command chmod. That because I didn't understand how it works and I feared breaking things. Today though, I learned how easy it is actually. No, not to break things, but to use the chmod command.

A Unix system allows for multiple users with different access rights, which can be changed in the shell by using this command.

The permissions are for reading, writing and executing (rwx) and are expressed for all three types of users a file or folder has. It will come in the form of rwxrwxrwx where the first batch of three characters (rwx), belong to the owner, the second to the group, and the third to all the other users (owner/group/other).

Sure, (rwx rwx rwx) would mean that everybody has all the access rights to that particular file or folder. And we all know that's not a good idea. So, most often you'll see something like rw-r--r-- which means that only the owner has the right to read and write, while everybody else can only read that particular file.

Now onto chmod, which can be used with either a symbolic or a numeric notation for the access settings. You've probably seen somebody else type chmod 644 file_name on your computer, leaving you wondering about what that means.

That's the numeric notation.

If you think about the access rights as a series of bits, the whole thing would look like this:

rwx rwx rwx = 111 111 111
rw- r-- r-- = 110 100 100
rw- r-x --- = 110 101 000

That translates into

rwx rwx rwx = chmod 777
rw- r-- r-- = chmod 644
rw- r-x --- = chmod 650

because in binary notation:

100 = 4
101 = 5
110 = 6
111 = 7

And now you've got a simple rule on how to construct your chmod command depending on what permissions you need to set.

The rwxr--r-- access rights means chmod 744, rw-r----- is chmod 640, and so on.

Simple enough, right?

Write to file with JavaScript and Node.js

Sometimes, as a programmer, you might need to write something to a file on the local file system. And that can be a piece of cake, case in which you'll use your favorite text editor to do it manually, but other times, it needs to be something complex and dynamic and you want your JavaScript to do it for you.

Here's how:

We'll first require the fs module from Node.js into our JS file.

const fs = require('fs');

Then we'll grab our content:

const content = 'Hello World!';

And finally we'll use the writeFile function from the fs module to populate our file. We need to provide the name of our file, the data or content to populate it with, the options (optional - for encoding, modes or flags) and a callback (also optional - to show the error message should one arise).

fs.writeFile(filename, data, [options], [callback]);

Here I've given it the a+ flag - "Open file for reading and appending. The file is created if it does not exist.". The encoding defaults to 'utf8' if none is given.

fs.writeFile('file.txt', content, { flag: 'a+' }, (err) => {
  if (err) throw err;
});

Currying in JavaScript

No, this has nothing to do with those delicious Indian curry dishes you might be thinking about, but with a functional technique used in JavaScript.

It seems confusing at first, but currying is simple. If you've never heard of it before, it's because this concept isn't native to JS.

Basically, it allows you to transform a function like f(a, b, c) into something like f(a)(b)(c). What that means is that you can split up a function with multiple arguments into a sequence of functions with one argument each.

Let's take a basic example.

const newUser = function(name, age, skill) {
  return {
    name,
    age,
    skill
  }
}
	
newUser("John", 27, "JS")

Now to the curry part:

const newUser = function(name) {
  return function(age) {
    return function(skill) {
      return {
        name,
        age,
        skill
      }
    }
  }
}
	
newUser("John")(27)("JS")

Add in some arrow functions and voila:

const newUser = 
  name => 
    age => 
      skill =>
      {
        name,
        age,
        skill
      }

The purpose of all this you might ask?

Think about situations when you don't have the complete data available in the beginning and you still need your function to gradually pass through your app and receive its arguments step by step as more and more data is arriving, until you add the final argument and receive the output.

Git delete all tags

Used to mark specific commits on git and often used to mark product releases on Github, git tags are important. But sometimes, you just need to delete them.

Here's a simple way to do that:

  • Delete all remote tags
git tag -l | xargs -n 1 git push --delete origin
  • Delete local tags
git tag | xargs git tag -d
  • Check if any tags are left
git tag

Lists and Recursion in Elixir - Flatten a list

While reading Dave Thomas's book, Programming Elixir, I stumbled upon an exercise.

You're supposed to write a flatten(list) function that takes a list as a parameter. That list may contain any number of sublists, which themselves may contain sublists ... Your function should return all the elements of these lists in a single flattened list, all the while preserving the order of the elements.

In the beginning, it sounded a bit hard (especially since he mentioned in the book that the exercise it's hard), but after enough playing with the idea, I got to a fairly simple solution, simpler than what I thought it would be and the solutions I've found so far on the internet.

The result should look something like this:

iex> MyList.flatten([ 1, [ 2, 3, [4] ], 5, [[[6]]]])
[1,2,3,4,5,6]

Now the function:

defmodule MyList do
  def flatten([]), do: []
  def flatten([head | tail]) when is_list(head) do
	  flatten(flatten(head) ++ tail)
  end
  def flatten([head | tail]), do: [head | flatten(tail)]
end

At first I thought it wouldn't work, but tested it and got surprised.

The flatten function takes care of 3 cases:

  • the given list is empty
  • the head of the list is in itself a list, in which case it should be flattened
  • the head is not a list, in which case we continue with flattening the tail

Parsing a date string into a date sigil in Elixir

What I was trying to achieve, was to get a person's date of birth from a date_input and calculate the age of that particular person. The problem was that the input was giving back a string like "yyyy-mm-dd" with the date, while I needed a date sigil of the form ~D[yyyy-mm-dd] to use with the diff/2 function.

IO.inspect(date_of_birth) "1978-06-11"

So I learned that you can use the from_iso8601!/1 function to parse the date from a string to an Elixir Date sigil.

IO.inspect(Date.from_iso8601!(date_of_birth)) ~D[1978-06-11]
def calculate_age(date_of_birth) do
	date_of_birth
		|> Date.from_iso8601!()
		|> calculate_date_diff()
		|> div(365)
end
defp calculate_date_diff(date) do
	Date.diff(Date.utc_today(), date)
end

Why the private calculate_date_diff() function? Because the Date.diff() takes the oldest date as its second parameter, while using the Elixir pipeline adds the previous functions's result as a first parameter to the next function.