Recent blog posts

Connecting a Cloudflare domain to my Netlify site

This post shows how to connect a domain name registered with Cloudflare to a website hosted on Netlify.

I assume the site is already deployed to Netlify, under a default Netlify domain name.

1. Register the domain name

Log into Cloudflare. Under Domain Registration, click on Register Domains, in the left sidebar.

Enter the desired domain name into the search box, and proceed with registration and payment.

2. Update Netlify settings

In the Netlify Site settings, under Domain management, add the new registered domain.

3. Update the DNS settings on Cloudflare

In the Cloudflare dashboard, click on the domain name and then DNS in the sidebar.

Add two DNS records: one for the apex domain cesareferrari.dev, and one for www. The DNS records are of type CNAME, and they both point to apex-loadbalancer.netlify.com

The records should look similar to these:

CNAME   cesareferrari.dev   apex-loadbalancer.netlify.com   Proxied   Auto
CNAME   www                 apex-loadbalancer.netlify.com   Proxied   Auto

After propagation, the site should load at the correct domain.

Basic mobile menu

Basic mobile menu

I need to create a simple menu for my mobile site.

Desired functionality

When on mobile, we should see a hamburger icon and some text that says Site menu.
The list of navigation links should be hidden at this stage.

When we tap on the hamburger icon, the navigation links will be revealed and displayed underneath. At the same time, the hamburger icon should be replaced by a close icon, represented by an “X”.

Tapping on the close icon, hides the navigation links again and replaces the close icon with the original hamburger icon.

The main navigation element for the site is a <nav> containing the list of navigation links.
The nav element has an id attribute of navigation-menu. The id will help us target this element with Javascript.
This element should be hidden from view when the page loads, so it has a hidden class on it.

    <nav id="navigation-menu" class="hidden" />
        <a href="...">...</a>
        <a href="...">...</a>
        <a href="...">...</a>
        <a href="...">...</a>
    </nav>

Open button, close button, and label

Buttons for opening and closing the navigation are plain svg images.

Hamburger button Close button

In the sample code below, the buttons are img elements with appropriate ids so they can be targeted later by Javascript.
The close menu button is hidden by default.

    <img src="hamburger.svg" id="open-menu-btn" alt="Open Menu" />
    <img src="close-btn.svg" id="close-menu-btn" alt="Close Menu" class="hidden" />

The menu label is a <span> element with the text “Site menu” and an id of site-menu-label.

<span id="site-menu-label">Site menu</span>

Now that we have all the html elements in place, I can add the Javascript. In my script I need to grab the four elements that make up the navigation system: navigation element, open menu button, close menu button, and label, and store a reference of them in four variables:

const openMenuBtn = document.querySelector("#open-menu-btn");
const navigationMenu = document.querySelector("#navigation-menu");
const closeMenuBtn = document.querySelector("#close-menu-btn");
const siteMenuLabel = document.querySelector("#site-menu-label");

The script functionality is very simple. All I need to do is hide the elements that are shown initially, and show the elements that are hidden, when an element is tapped by the user.

The element tapped is either the open menu button or the close menu button. The way to show or hide an element is to add (or remove) a class named hidden. I can then write a function in my script that does just that. The function accepts an array of the four elements that need to be shown or hidden.

  const elementList = [openMenuBtn, navigationMenu, closeMenuBtn, siteMenuLabel];

  function toggleElements (elements) {
    for (let element of elements) {
      element.classList.toggle("hidden");
    }
  }

This function runs when a click event is triggered. The event listener is added to the document and calls the toggleElements function only when we tap on one of the elements.

  document.addEventListener("click", (event) => {
    if (elementList.includes(event.target)) {
      toggleElements(elementList);
    }
  })

Below is the full script.

<script>
  const openMenuBtn = document.querySelector("#open-menu-btn");
  const navigationMenu = document.querySelector("#navigation-menu");
  const closeMenuBtn = document.querySelector("#close-menu-btn");
  const siteMenuLabel = document.querySelector("#site-menu-label");
  const elementList = [openMenuBtn, navigationMenu, closeMenuBtn, siteMenuLabel];

  function toggleElements (elements) {
    for (let element of elements) {
      element.classList.toggle("hidden");
    }
  }

  document.addEventListener("click", (event) => {
    if (elementList.includes(event.target)) {
      toggleElements(elementList);
    }
  })
</script>

How to sort an array in Javascript

How to sort an array in Javascript

Here’s how to sort an array of objects in Javascript.

We start with an array of object like so:

const people = [] 

people.push({name: "John", age: 36, eyeColor: "hazel"});
people.push({name: "Pam", age: 63, eyeColor: "blue"});
people.push({name: "Tim", age: 24, eyeColor: "brown"});
people.push({name: "Julia", age: 20, eyeColor: "brown"});
people.push({name: "Roberta", age: 45, eyeColor: "green"});

We want to order the objects in the array by the age attribute, in descending order, from oldest to youngest.

Array has a sort() method that we can use in this case.

The method takes a function that can be used to specify the sort order of the elements in the array.

In our case, we want to sort by age descending, so we call sort() like so:

people.sort((a, b) => b.age - a.age);

sort() orders the array in place, so it mutates it. If we want to keep the array in its original state, we can use the toSorted() method, which behaves the same way, but returns a new array.

const peopleOrderedByAge = people.toSorted((a, b) => b.age - a.age);

Generating a new Rails app with specific software versions

Generating a new Rails app with specific software versions

Creating a new Rails application is simple enough. Just run rails new and a new functioning application, including its root directory and all necessary files are automatically generated for me.

But sometimes I want a little more control on what kind of libraries to use. What if I need to use one specific version of Ruby? And what if I want to use the latest version of Rails instead of the one already installed on my system?

This article shows the steps I take when creating a new Rails application, before running rails new so I can configure my application just the way I want it.

1. Create a new application directory

I like to start a new application by manually creating a new directory on my development computer. I then move inside the directory and create the necessary files inside of it.

In this example, the app is called my-app.

$ mkdir my-app

$ cd my-app

2. Set local version of Ruby

When I am inside the root directory I can go ahead and verify which versions of Ruby I have available on my system.

Since I use asdf as a version manager, I list the Ruby versions on my computer with asdf list ruby:

$ asdf list ruby
  2.6.7
 *3.2.2

This tells me that I have two versions of Ruby installed: 2.6.7 and 3.2.2. The asterisk * marks the currently active version, 3.2.2. At this point I can decide if the current version is good enough for me or if I want a different one.

If I want a more recent Ruby, I can install it with this command:

$ asdf install ruby 3.3.0

For the purposes of this article, I will use Ruby 3.2.2, so I set the local desired version for this particular application with this command:

$ asdf local ruby 3.2.2

This will create a .tool-versions file inside the current directory specifying which Ruby to use:

# .tool-versions

ruby 3.2.2

3. Add Gemfile

Once Ruby is specified, the next step is to choose the Rails version for the new application.

I start off by adding a new Gemfile in the root directory, so I can specify the exact Rails version to use, and let Bundler take care of the installation. The simplest way to generate a Gemfile is with:

$ bundle init

This will generate a Gemfile inside the directory with content similar to this:

# Gemfile

# frozen_string_literal: true

source "https://rubygems.org"

# gem "rails"

The gem "rails" entry is commented out as an example.

4. Install latest version of Rails

To find the latest version of Rails I can look at the Ruby on Rails homepage. Currently it’s 7.1.3.2, so I will use that for my app.

By default, the line gem "rails" will install the latest version, so I open the Gemfile and uncomment the # gem "rails" line, like so:

# Gemfile

gem "rails"

Then I run bundle install which will take care of installing Rails and all the required gems. The command will also generate a Gemfile.lock file to lock all the various gem versions.

To verify that the desired versions of Ruby and Rails are active, I run these commands:

$ ruby -v
ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-linux]
$ rails -v
Rails 7.1.3.2

I am now ready to generate the Rails app.

5. Create new Rails app

Now that I have all the desired versions of the libraries, I am finally ready to create the Rails app with the rails new command.

Since I want the Rails application to be generated inside the current directory, I pass a . (dot) as the last option on the command line:

$ rails new .
       exist
      create  README.md
      create  Rakefile
      create  .ruby-version
      create  config.ru
      create  .gitignore
      create  .gitattributes
    conflict  Gemfile
Overwrite /home/cesare-mini/Sites/horton-township/Gemfile? (enter "h" for help) [Ynaqdhm]

The rails new script is set to create its own Gemfile, but I already have a Gemfile in the directory, so the process stops to ask if I want to overwrite it. That Gemfile was only meant for installing Rails itself, so I don’t need it anymore. I type y to confirm the overwrite. This will allow rails new to go ahead and finish setting up the application.

Once the process is finished I can verify that the application works correctly by running:

$ bin/rails server

This will start the application on http://localhost:3000 and show the default Rails welcome screen.

Rails smoke test

At the bottom of the screen, I can also see the exact software versions used for this application.

Conclusion

In this article we have seen one way in which we can control and specify the exact library versions our Rails application uses.

Photo by Ann Marie Kennon

Adding Tailwind CSS to a Rails application

Adding Tailwind CSS to a Rails application

In this post I describe how to generate a new Rails application with Tailwind as the CSS framework.

I also describe how to add Tailwind to an existing application, and how to configure Tailwind and add some basic classes and custom fonts.

Let’s start with generating a new Rails application with Tailwind as the default CSS framework

Generating a new application with Tailwind CSS

To generate a brand new application that includes Tailwind to handle CSS, I run this command in the terminal:

$ bin/rails new -css tailwind application-name

This will set up the application with Tailwind right off the bat and there’s nothing else to do.

Adding Tailwind CSS to an existing application

Sometimes, I need to add Tailwind to an existing Rails application. In this case I first need to add the tailwindcss-rails gem to the bundle and then install Tailwind in the application.

$ bundle add tailwindcss-rails
$ bin/rails tailwindcss:install

This command will perform a series of tasks:

  1. It will add a stylesheet tag for Tailwind in the application layout

    <%= stylesheet_link_tag "tailwind", "inter-font", "data-turbo-track": "reload" %>
    

    It will also add a container with some Tailwind classes to the <body> tag:

    <main class="container mx-auto mt-28 px-5 flex">
    
  2. It will create the app/assets/builds directory where Tailwind build files go.

  3. It will add the default Tailwind configuration files

    config/tailwind.config.js
    app/assets/stylesheets/application.tailwind.css
    
  4. It will add a Procfile.dev file to start the tailwind:watch process

  5. It will add the bin/dev script for starting the application in development mode.

Configuration files

In order to work properly, Tailwind needs a number of configuration files.

The main configuration file is config/tailwind.config.js.

This file is used for specifying plugins, themes, and other pieces of information needed.

The Tailwind input file is generated at

app/assets/stylesheets/application.tailwind.css

I use this file for custom classes that are used across the application, like classes for buttons for example, or default styles for headers, main text, etc.

The output file lives in app/assets/builds/tailwind.css. This file is generated by the Tailwind build command and includes all the classes and definitions needed by the application.

In development we want to run Tailwind in watch mode so changes are automatically reflected in the pages while developing the site.

For this purpose, the Procfile.dev file runs a tailwindcss:watch process when the application is started using bin/dev.

# Procfile.dev

web: bin/rails server --binding=0.0.0.0
css: bin/rails tailwindcss:watch

Initial styles

Once Tailwind is first added, it will by default remove all the styles from the pages, so everything appears unstyled.

The <main> container added by the Tailwind installation will also be styled with a flex class which places all the elements on the page side by side.

I usually remove this flex class and add a prose class which will add sensible typographical styling to the pages and make them look presentable. Once I have decided how to actually style the application, I remove these initial styles and add my own.

# app/views/layouts/application.html.erb

<main class="prose container mx-auto mt-28 px-5">

Photo by Peter Simmons

Adding Open Graph and Twitter Cards meta tags to a Rails application

Adding Open Graph and Twitter Cards meta tags to a Rails application

There is no doubt that social media meta tags embedded into a web page help with engagement when the page is shared on sites like Twitter (now renamed “X”) or Facebook.

When links are shared on those platforms a robot goes back to the linked page and searches inside of it for meta information: things like “page title”, “cover image”, “embedded media”, and more.

If found, these snippets get formatted into a visually pleasant box with important information like page title, cover image, etc. This box is then placed inside the post instead of the original boring, plain text link.

It is the responsibility of the site owner to provide the appropriate meta information inside meta tags included in the html pages. This information needs to follow a specific format, or protocol, set up by the social media platforms.

There are two main types of social media meta tags:

  1. Open Graph tags
  2. Twitter Card tags

Open Graph

The Open Graph protocol was promoted by Facebook and provides guidelines on how to create meta tags that give context to information, images, videos, and so on, that a social media site can interpret and display appropriately.

Open Graph is not only used by Facebook, but also by Linkedin and Twitter.

Below is an example of a Facebook post enhanced by Open Graph meta tags embedded in the linked web page.

Facebook Open Graph example

Twitter Cards

In addition to Open Graph, Twitter also uses a separate protocol that they have developed called Twitter Cards.

Twitter Cards let you attach photos, videos, and media to Tweets, which help drive traffic to the website. Here’s an example of how a tweet can embed media via Twitter Cards:

Twitter Card example

Social media meta tags are added to the <head> section of the web page and look like these:

<head>
  <meta property="og:title" content="Adding Open Graph">
  <meta property="og:type" content="article">
  <meta property="og:description" content="Post description">
  <meta property="og:site_name" content="Ferrari Web Development">
  <meta property="og:url" content="http://example.com/blog/opengraph">
  <meta property="og:image" content="http://example.com/assets/267350.jpg">

  <meta name="twitter:title" content="Adding Twitter Cards">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:description" content="Post description">
  <meta name="twitter:site" content="@cesareferrari">
  <meta name="twitter:image" content="http://example.com/assets/267350.jpg">
</head>

When developing a web site, I use a Ruby library called meta-tags to handle generating and embedding all meta tags into a Rails application, including Open Graph and Twitter tags.

The meta-tags gem

The meta-tags Ruby gem helps make a Rails application more SEO friendly.

It makes it easy to handle the process of defining and generating the meta tags that need to be included into the application’s layout template.

There are two main steps in using this gem:

  1. set needed meta tags with the set_meta_tag method
  2. display meta tags in the application layout with display_meta_tags

Both of these methods are provided by the meta-tags library. Let’s see in detail how to use it.

Install the gem with:

bundle add meta-tags

Add the display_meta_tags method call to the application layout inside the <head> element:

# app/views/layouts/application.html.erb

<head>

  <%= display_meta_tags site: "Ferrari Web Development" %>

</head>

This method takes a site: "..." parameter that we can set to a string with our site name. This string will appear in the page title.

Next, we can generate meta tags specific for each page in the page show template by calling the set_meta_tags method and passing the desired information.

Open Graph tags

Here’s a list of Open Graph tags that can be included in the web page:

For other available tags, check out the Open Graph documentation.

Here’s how to set these tags in the page view using set_meta_tags:

<% set_meta_tags og: {title: @post.title,
                      type: "article",
                      description: @post.blurb,
                      image: image_url(@post.cover),
                      url: request.original_url,
                      site_name: "Ferrari Web Development"} %>

Twitter Cards tags

Here’s a list of Twitter Card tags that can be included in the web page:

For other available tags, consult the Twitter Cards documentation.

Here’s how to set Twitter Card tags in the page view using set_meta_tags:

<% set_meta_tags twitter: {title: @post.title,
                            card: "summary_large_image",
                            description: @post.blurb,
                            site: "@cesareferrari",
                            image: image_url(@post.cover)} %>

Notes on URLs

Conclusion

This article describes how to set popular social media meta tags inside web pages. Meta tags are used by different platforms to format posts in a way that’s more appealing to their audience for the purpose of making posts more engaging and to promote clicks and shares.

The meta tags functionality is handled in a Rails application by a Ruby gem called meta-tags. This library has several methods for easily setting and displaying meta tags inside the page layout.

Photo by Pixabay

View All Posts →