Random Notes

This Git alias "del" efficiently deletes a local branch while ensuring it's up-to-date with the main (or master) branch. It automatically switches to the main branch, fetches updates from the remote, pulls changes, and deletes the specified branch.

You may add this alias to your git config file located at /Users/your_username/.gitconfig

[alias]
  del = "!f() { \
    git rev-parse --verify main >/dev/null 2>&1 && branch=main || branch=master; \
    git checkout $branch; \
    git fetch -p; \
    git pull; \
    git branch -D \"$@\"; \
  }; f"

 

See list of commits, first one on top:

git log

 

See all branches, with last commit on top of the list:

git branch -v

 

See your commits visualized directly in the Terminal:

# see all commits on the current branch
git log --graph

# see all commits on all branches
git log --graph --all

 

/* Nope */
font-size: var(--value) + var(--unit);

/* Yep */
font-size: calc(var(--value) * 1px);

 

another example:

.p {
  width: calc(var(--parentWidth) * var(--leftSize) - var(--padding));
}
--padding: 10px;

.class {
     	margin:
  		var(--padding)
  		calc(var(--padding) * -1)
  		var(--padding)
  		calc(var(--padding) * -1);
}

 

SCSS equivalent:

$padding: 10px;

.class {
	margin:
		$padding
		(-$padding)
		$padding
		(-$padding);
}

 

List local branches:

git branch

 

List remote branches:

git branch -r

 

Delete local branch:

git branch -d <branch-name>

 

Delete remote branch:

git push origin --delete <branch-name>

 

Manual

gem push \
  --key github \
  --host https://rubygems.pkg.github.com/USERNAME/GEMNAME \
  GEMNAME-1.0.0.gem

With rake release

# Add credentials
echo ":github: Bearer ${GH_TOKEN}" >> ~/.gem/credentials

# Define key for gem release
bundle config set --global gem.push_key github

# Release gem
rake release

Also check the following:

That you have allowed_push_host setup in you .gemspec file

# eg. https://rubygems.pkg.github.com/EffectivaStudio
spec.metadata["allowed_push_host"] = "https://rubygems.pkg.github.com/<ORGANIZATION_NAME>"

That the name of the gem name and repository name matches

# Repository url
# https://github.com/EffectivaStudio/some-gem-name

spec.name = "some-gem-name"

Error explanation:

The expected resource was not found.
Your repository and you gem name are mismatched.
PROTIP: check - and _

💣 When dealing with empty match:

"1. Price 3EUR".match(/(\d+)EUR/)[1]
# => 3

"1. Price EUR".match(/(\d+)EUR/)
# => This will throw an error


😎 Use:

"1. Price EUR"[/(\d+)EUR/, 1]
# => nil


👎 To avoid following situations:

# Possible solutions

# Rescue
"1. Price EUR".match(/(\d+)EUR/)[1] rescue nil
# => nil

# Global match
"1. Price EUR".match(/(\d+)EUR/) && $1
# => nil

# Variable
result = "1. Price EUR".match(/(\d+)EUR/)
result && result[1]

 

 

ActiveRecord::Querying::QUERYING_METHODS

#=> [:find, :find_by, :find_by!, :take, :take!, :first, :first!, :last, :last!, :second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!, :forty_two, :forty_two!, :third_to_last, :third_to_last!, :second_to_last, :second_to_last!, :exists?, :any?, :many?, :none?, :one?, :first_or_create, :first_or_create!, :first_or_initialize, :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, :create_or_find_by, :create_or_find_by!, :destroy_all, :delete_all, :update_all, :touch_all, :destroy_by, :delete_by, :find_each, :find_in_batches, :in_batches, :select, :reselect, :order, :reorder, :group, :limit, :offset, :joins, :left_joins, :left_outer_joins, :where, :rewhere, :preload, :extract_associated, :eager_load, :includes, :from, :lock, :readonly, :extending, :or, :having, :create_with, :distinct, :references, :none, :unscope, :optimizer_hints, :merge, :except, :only, :count, :average, :minimum, :maximum, :sum, :calculate, :annotate, :pluck, :pick, :ids]

 

Edit sudoers file or add new in /etc/sudoers.d

Defaults env_keep += "ENV_VAR"

note: save and close editor since visudo creates temp file and saves suders file only when you close editor

config/initializers/mongoid.rb

# frozen_string_literal: true

if defined?(Mongoid)
  # GlobalID is used by ActiveJob
  Mongoid::Document.include GlobalID::Identification
  Mongoid::Association::Proxy.include GlobalID::Identification
end

 

rake -T

will only show you documented tasks. In order to list all the tasks, you need to append the -A option.

rake -AT

Display the tasks (matching optional PATTERN) with descriptions, then exit. -AT combination displays all of the tasks contained no description.
Please note that passing -TA options won't work, however, you can pass them separately.

rake -TA   # doesn't work 
rake -T -A # works

All the above commands could be called via rails instead of rake inside a rails project.

rails -AT
class Chat < ApplicationRecord
  has_many :messages, dependent: :destroy
end

Let's say we already have some chats with messages in our database.

irb(main):001:0> chat = Chat.first
  Chat Load (0.4ms)  SELECT "chats".* FROM "chats" ORDER BY "chats"."id" ASC LIMIT $1  [["LIMIT", 1]]
=> #<Chat id: 1>

irb(main):002:0> chat.messages
=> #<ActiveRecord::Associations::CollectionProxy [#<Message id: 1>, #<Message id: 2>]>

Creating a new instance of Chat and passing in :id and :messages like so

irb(main):003:0> Chat.new(id: 1, messages: [])
  Message Load (0.9ms)  SELECT "messages".* FROM "messages" WHERE "messages"."chat_id" = $1  [["chat_id", 1]]
   (0.2ms)  BEGIN
  Message Destroy (0.3ms)  DELETE FROM "messages" WHERE "messages"."id" = $1  [["id", 1]]
  Message Destroy (0.2ms)  DELETE FROM "messages" WHERE "messages"."id" = $1  [["id", 2]]
   (1.8ms)  COMMIT
=> #<Chat id: 1>

will actually fire up a DELETE  SQL statement and destroy our messages.

If you have ever opened your HTML source in the browser and wondered which templates were rendering which part of the page, this feature is for you.

 # Render template filenames as comments in HTML
 config.action_view.annotate_template_file_names = true

 

Ruby 2.7 introduced a shorthand syntax (...) for forwarding arguments to methods.

# using args, kwargs, and block arguments
def perform(*args, **kwargs, &block)
  block.call(args, kws)
end

# using the new syntax
def call(...)
  perform(...)
end

 

Using  `target="_blank"` can be dangerous and affect performance since `window.opener` will have reference to previous window.

 

window.opener returns a reference to the window that opened the window using `open()`.

( if the window A opens a window B, B.opener returns A)

 

To prevent this (set window.opener to null ) use ` rel="noopener" ` for older browser support use  ` rel="noreferrer`

 

Good reads:

https://mathiasbynens.github.io/rel-noopener/

https://css-tricks.com/use-target_blank/

Useful when you need to accept any number of parameters, but you actually don't care about them or you just want to pass them away to the superclass method.

class Bar
  def do_something(*args)
    puts "Passed args: #{args.inspect}"
  end
end

class Foo < Bar
  def do_something(*)
    super
  end
end

Foo.new.do_something("hello", "world")
#=> Passed args: ["hello", "world"]

Sometimes we do not follow all best guidelines, creating new branches because there is a point that makes no sense if you have just typo in translation and you amend your last commit or you squash your commits, there will be no harm but in situations when you must work with a teammate on sam branch there is one safer solution than

git push --force

`--force-with-lease` refuse to update a branch unless it is the state that we expect; i.e. nobody has updated the branch upstream

git push --force-with-lease

 

note: this is not a bulletproof solution but is still better than just using `--force`

here is a good article explaining it with potential pitfalls https://blog.developer.atlassian.com/force-with-lease/

If you develop gem and want to test changes in real-time without pushing code you could use path instead of git repo but this has few disadvantages if you need a test that code is working on multiple projects you need to add that change to every single project and later remember to remove this, but here come local git repos to rescue.

Simply tell bundler to use local version instead.

$ bundle config local.my_gem ~/projects/my_gem

When you are done with testing just remove the binding.

$ bundle config --delete local.my_gem

Pluck all the ID's for the ActiveRecord relation using the table's primary key

User.ids 
# the same as:
User.pluck(:id) 
#=> SELECT users.id FROM users