Vincent is Coding
March 23rd, 2024 Ruby on Rails

Normalise a value in Rails 7.1

One things I noticed whilst developing Scribbles is that I needed a quick way to just normalize some properties as a blog was saved/updated.

Scribbles allows you to set up Tinylytics using the special site embed id and also various other 3rd party services like status.lol or shoutouts.

One thing I noticed is that sometimes things broke because a space was at the start or end of the pasted value. So you can imagine if you're trying to append that value to a URL, it wouldn't work and not do anything useful.

Thankfully Rails 7.1 has a new normalizes hook, that basically does everything for you. And it's super easy to set up in the model.

Here is how I'm using it to make sure no space is introduced in the Tinytlytics embed code:

normalizes :tinylytics_site_id, with: -> tinylytics_site_id {
  tinylytics_site_id.strip
}

Super easy and very useful. Another example was status.lol because there is some confusion on what an "address" is. That meant that sometimes I would get a full url, or something else in there. Here is how I handle most of it now:

normalizes :status_lol_address, with: -> status_lol_address {
  status_lol_address.strip
   .gsub("https://status.lol/", "")
   .gsub("status.lol/", "")
}

That handles a lot of the edge cases I came across and it just works.