Updating ActiveRecord models without loading an instance using Postgresql

There're sometimes that we need to update an ActiveRecord Model but it is not necesary to load an instance, the normal flow would be the following:

profile = UserProfile.find_by(user_id: id)
profile.update(last_seen_at: Time.now)

The problem with this is that we load a useless instance of UserProfile, it is not needed, in a high traffic sites, an extra select query can count a lot, but luckly, Rails has addressed this with upsert command:

UserProfile.upsert({ last_seen_at: Time.now, user_id: id }, unique_by: :user_id)

This will use native Postgresql upsert command to update a record if it exists or insert a new one and no select will be performed, everything in a single query instead of two.

To make it really work, you need to modify your created_at and updated_at columns to have default current_timestamp

NIX node manager

Use n, an extremely simple Node version manager that can be installed via npm.

Say you want Node.js v12.10.0 to build Ghost template.

npm install -g n   # Install n globally
n 12.10.0          # Install and use v12.10.0
Usage:
n                            # Output versions installed
n latest                     # Install or activate the latest node release
n stable                     # Install or activate the latest stable node release
n <version>                  # Install node <version>
n use <version> [args ...]   # Execute node <version> with [args ...]
n bin <version>              # Output bin path for <version>
n rm <version ...>           # Remove the given version(s)
n --latest                   # Output the latest node version available
n --stable                   # Output the latest stable node version available
n ls                         # Output the versions of node available

Using Rails to migrate columns from JSON to JSONB in Postgresql

Postgres offers data type json to store any structure easily, but one dissadvantage is that filtering by properties stored in the json column are super slow, one simple fix before refactoring the whole implementation is to migrate the column to be jsonb, since it is stored in binary form, it supports indexes, a easy and safe way to do it is as follows:

class ModifyJSONDataDataType < ActiveRecord::Migration[6.0]
  def up
    add_column :table_name, :data_jsonb, :jsonb, default: '{}'

    # Copy data from old column to the new one
    TableName.update_all('data_jsonb = data::jsonb')

    # Rename columns instead of modify their type, it's way faster
    rename_column :table_name, :data, :data_json
    rename_column :table_name, :data_jsonb, :data
  end

  def down
    safety_assured do
      rename_column :table_name, :data, :data_jsonb
      rename_column :table_name, :data_json, :data
    end
  end
end

Then, using another migration(due the ability to disable transactions), add an index to it

class AddIndexToDataInTableName < ActiveRecord::Migration[6.0]
  disable_ddl_transaction!

  def change
    add_index :table_name, :data, name: "data_index", using: :gin, algorithm: :concurrently

    # You can even add indexes to virtual properties:
    # add_index :table_name, "((data->'country')::text)", :name => "data_country_index", using: 'gin', algorithm: :concurrently
  end
end

The slice_when method in Ruby

Creates an enumerator for each chunked elements. The beginnings of chunks are defined by the block.

This method splits each chunk using adjacent elements, elt_before, and elt_after, in the receiver enumerator. This method split chunks between elt_before and elt_after where the block returns true.

The block is called the length of the receiver enumerator minus one.

The result enumerator yields the chunked elements as an array. So each method can be called as follows:

enum.slice_when { |elt_before, elt_after| bool }.each { |ary| ... }

For example:

Return adjacent elements from this array [1, 2, 3, 5, 6, 9, 10] in chunked elements as an array.

[1, 2, 3, 5, 6, 9, 10].slice_when {|i, j| i+1 != j }.to_a
=> [[1, 2, 3], [5, 6], [9, 10]]

The each_cons method in Ruby

Iterates the given block for each array of consecutive <n> elements. If no block is given, returns an enumerator.

irb(main):001:0> [1,2,3,4].each_cons(2).to_a
=> [[1, 2], [2, 3], [3, 4]]

irb(main):002:0> [1, 2, 3, 5, 6, 9, 10].each_cons(2).to_a
=> [[1, 2], [2, 3], [3, 5], [5, 6], [6, 9], [9, 10]]

Print any two adjacent words in a given text:

def print_adjacent_words(phrase)
   phrase.split.each_cons(2) do |words|
     puts adjacent_word = words.join(" ")
   end
end
irb(main):025:0> print_adjacent_words("Hello Darkness my old friend")
Hello Darkness
Darkness my
my old
old friend
=> nil

Optional Chaining Operator (?) and Nullish Coalescing Operator (??)

Optional Chaining Operator(?) (**)

//Car object
const car = {
  attributes: {
   year: 2021,
   model: "Ferrari"
  }
}

Before in javascript to validate that the attributes of an object exist, it was necessary to use the And operator (&&) to validate if the attributes of the object existed.

See the following example:

if (car && car.attributes && car.attributes.model) {
  console.log('Exist',  car.attributes.model)
} else {
  console.log('Do not exist')
}

# => "Exist Ferrari"

Now with Optional Chaining Operator (?) We can validate if the property exit will return undefined if the property attributes or model doesn’t exist.

if (car?.attributes?.model) {
  console.log('Exist',  car.attributes.model)
} else {
  console.log('Do not exist')
}

# => "Exist Ferrari"

Nullish Coalescing Operator(??) (**)

//Car object
const car = {
  attributes: {
   year: 2021,
   model: "Ferrari"
  }
}

If we want to get the car model then we would like below:


console.log(car.attributes.model);
# => "Ferrari"

Now the new car object does not have the model property, so we get an undefined value

//Car object
const car = {
  attributes: {
   year: 2021,
  }
}
console.log(car.attributes.model);
# => "undefined"

To avoid the undefined value the OR (| |) operator can be used, It will now return the value BMW because the property model is undefined. But what if the name property is empty like below example

console.log(car.attributes.model | | "BMW" );
# => "BMW"

Now the problem is when the property model exists but has an empty, undefined or null value we will get the BMW value and this is not right.

//Car object
const car = {
  attributes: {
   year: 2021,
   model: ""
  }
}
console.log(car.attributes.model | | "BMW" );
# => "BMW"

The solution for this problem is to use the Nullish Coalescing Operator (??), Which will print the result as an empty string.

console.log(car.attributes.model ?? "BMW" );
# => ""

Ruby Double star (**)

def hello(a, *b, **c)
  return a, b, c
end

a is a regular parameter. *b will take all the parameters passed after the first one and put them in an array. **c will take any parameter given in the format key: value at the end of the method call.

See the following examples:

One parameter

hello(1)
# => [1, [], {}]

More than one parameter

hello(1, 2, 3, 4)
# => [1, [2, 3, 4], {}]

More than one parameter + hash-style parameters

hello(1, 2, 3, 4, a: 1, b: 2)
# => [1, [2, 3, 4], {:a=>1, :b=>2}]

THE MEANING AND POWER OF WORDS (ONLINE)

If the interpretation of messages in an oral face-to-face conversation is too subjective —even with clear tones of voice and body language— imagine when communicating through a screen! We have to be assertive AF!   I believe that to be assertive through texts messages we need to consider WRITING RULES such as spelling (correct use of punctuation marks, accents, and capital letters), syntax (the way in which words and the groups they form are combined to express meanings, as well as the relationships established between all these units), and semantics (the meaning and changes in the meaning of words and expressions).   To the point> Semantically speaking, it is important to consider that there are two divisions in this area: denotation and connotation.   The denotation: This is the original or formally accepted expression of the word, this is the word that is formally found in encyclopedic dictionaries and is universally accepted.   Connotation: Connotation is the alternate or secondary form in which a word is used, such as is the case with the word donkey, which in denotative form implies the equine type animal, and in the connotative form the dumb man or person.   Get it? So, we have to be super conscious of the meaning and power of the words we choose when having written conversations. Is like: the connotation of the words OCUPO and NECESITO could be similar, but the correct thing to say, because of the denotation of the words, is NECESITO QUE ME AYUDES ME ACORREGIR ESTE CODIGO.   It is better that way so we don't misunderstand things. And if so, nothing better than talking to eliminate misunderstandings, right? Talking-communicating is the best way to understand each other, the best way to organize ourselves.   It is good to be sincere and direct. But, we must try to be assertive. And, in my opinion, there is a fine line between being assertive, sincere, or direct > and rude. To be assertive the message must get through to the receiver correctly, otherwise, it's not.

momazo