Today I learned about Reddit API existance and Rails uuid

  • Written on: Su Dec 2020
  • Last update: Su Dec 2020

Reddit API

One thing I discovered today is that, you can easily get subreddit informations without parsing them! Reddit gives you a direct formatted JSON you can use to get post informations

Per example, if you GET https://www.reddit.com/r/murdermittens.json, it will returns you a pretty JSON.

With that, you can paginate, filter and do some other stuff as specified in their documentation https://www.reddit.com/dev/api/

Using uuid on Rails

I've got one problem this morning on how to handle uuids with Rails. Following some blog articles, some recommends to use gen_random_uuid() as default in your tables.

t.uuid :uuid, null: false, default: 'gen_random_uuid()', index: { unique: true }

This seems to work well but one thing I stubble on was to create a new entry and get the uuid right away. Because the gen_random_uuid() thing is called on database insertion, we cannot get it right away with Rails, it's always nil.

The workaround I've found is to inject a uuid myself on initialize. When the model is initialized and there is no uuid associated yet, we generate it using the Gem securerandom and assign it to our record.

require 'securerandom'

after_initialize :generate_uuid, unless: :has_uuid

def generate_uuid
  self.uuid = SecureRandom.uuid if defined? self.uuid
end

def has_uuid
  return self.has_attribute?(:uuid) && self.uuid.present?
end

To avoid repeating this code in every model, you can put it in the application_record.rb since all our models extends from that.

require 'securerandom'

class ApplicationRecord < ActiveRecord::Base
  after_initialize :generate_uuid, unless: :has_uuid

  self.abstract_class = true

  def generate_uuid
    self.uuid = SecureRandom.uuid if defined? self.uuid
  end

  private

  def has_uuid
    return self.has_attribute?(:uuid) && self.uuid.present?
  end
end

Now whenever you create a new record, the uuid will be available right after the creation.