Random Notes

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

 

To create a hyperlink in a terminal execute following code:

echo -e '\e]8;;https://effectiva.hr\aEffectiva studio\e]8;;\a'

Result:

* some terminals may not support hyperlinks

Use this comments to "tag" commands in terminal so it's easier to find it later.

df -h #disk #useful
git reset HEAD~ #git #undo #undocommit #useful

Than you can use:

history | grep "# useful"

or reverse search with CTRL+R

Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure:

  • abstract 
    Must be implemented by every subclass.
  • optional
    Already have some default implementation, but still can be overridden if needed.
  • hook 
    Optional step with an empty body. 
    Usually, hooks are placed before and after crucial steps of algorithms, providing subclasses with additional extension points.

build_stubbed is the younger, more hip sibling to build; it instantiates and assigns attributes just like build, but that’s where the similarities end. It makes objects look like they’ve been persisted, creates associations with the build_stubbed strategy (whereas build still uses create), and stubs out a handful of methods that interact with the database and raises if you call them. This leads to much faster tests and reduces your test dependency on a database.

Use Factory Girl's build_stubbed for a Faster Test Suite