Tag rails logs with useful information

Just learned about tagged logging in rails. Did you know you can tag a log by using

logger.tagged('Your Tag') { logger.info('Message') }


You can also do it globally with

# config/application.rb
config.log_tags = [:method_on_request_object, lambda { |request| request.method.modifier_method }]


Add client Device OS and OS Version information to logs (requires clients to send X-OS and X-OS-Version headers)

# config/application.rb
config.log_tags = [ :request_id, lambda { |request| "#{request.headers['HTTP_X_OS']} #{request.headers['HTTP_X_OS_VERSION']}" } ]


828
Joe

Limited has_many associations

# app/models/user.rb
has_one :four_car_garage
has_many :cars
validates :cars, length: { maximum: 4 }


Joe

How to really!! quit vim

In terminal

vim todo.txt


Colon (:) (lowercase) q vim :q

Just don't use MacVim @joe :D

1.07 Thousand
Ali

How to quit Vim

  1. Install latest version of Vim
  2. Open a file in Vim
  3. ⌘-Q and close the terminal
  4. Reopen terminal

This is obviously a joke, it's impossible to quit Vim.

1.07 Thousand
Joe

Create idempotent migrations

When you want to write destructive migrations please use if_exists: true when you’re trying to remove a table and check for a table existence when you want to add or remove a column ActiveRecord::Base.connection.table_exists?

Case 1:

def up
  drop_table :kittens, if_exists: true
end


Case 2:

def up
  return unless ActiveRecord::Base.connection.table_exists?(:kittens)
  add_column :kittens, :kind, :integer
end


Ali

Add spacers to your macOS app dock to make groups

Open term (or equivalent) and paste the following one-liner:

defaults write com.apple.dock persistent-apps -array-add '{tile-data={}; tile-type="spacer-tile";}'; killall Dock


When the Dock restarts, there should be a draggable blank space that you can move anywhere. Repeat to your heart's desire.

1.07 Thousand
Jeff

Send messages to Slack using cURL

Slack allows you to send messages via the Webhooks service

Create a webhook for any channel and then you can send notification using curl.

$ curl -X POST -H 'Content-type: application/json' --data '{"text": "Something important"}'  https://hooks.slack.com/services/YOUR/TOKENIZED/URL

Setting Up Incoming Webhooks


Incoming webhooks are a simple way to post messages from apps into Slack. To set up an incoming webhook, you need to create a Slack app and enable incoming webhooks in the app settings. Here’s a step-by-step guide to setting up incoming webhooks:

  1. Log in to your Slack account and navigate to the Slack API main page.
  2. Click the “Create an app” button and select “From scratch.”
  3. Enter a name for your app and select the workspace where you want to deploy it.
  4. Click the “Create App” button.
  5. In the app settings, navigate to the “Features” section and click on “Incoming Webhooks.”
  6. Toggle the switch to enable incoming webhooks.
  7. Click the “Add New Webhook to Workspace” button.
  8. Select the channel where you want to post messages and click “Allow.”

By following these steps, you can create a Slack app and set up an incoming webhook to start sending messages to your chosen channel.

Creating a Payload


To send a message via an incoming webhook, you need to create a payload that contains the message text and some options. Here’s how to create a payload:

  1. Determine the content type of your payload. For incoming webhooks, the content type is always “application/json.”
  2. Create a JSON object that contains the message text and any additional options you want to include. For example:
    1. { "text": "Hello, Slack!", "username": "WebhookBot", "icon_emoji": ":ghost:" }
      
  3. Use a tool like curl to send the payload to the incoming webhook URL.
By creating a properly formatted JSON payload, you can ensure that your message is correctly sent to Slack via the incoming webhook.

Sending Messages with cURL


cURL is a command-line tool that you can use to send messages to Slack via an incoming webhook. Here’s an example of how to use cURL to send a message:

  1. Open a terminal and navigate to the directory where you want to send the message
  2. Create a file with a .json extension that contains the payload. For example, create a file named message.json with the following content:
    1. { "text": "Hello, World!" }
      
  3. Use the cURL command to send the payload to the incoming webhook URL: 
    1. curl -X POST -H 'Content-Type: application/json' --data @message.json https://hooks.slack.com/services/YOUR/TOKENIZED/URL
      
By following these steps, you can use cURL to send a message to Slack via an incoming webhook.

Testing and Troubleshooting


When testing and troubleshooting incoming webhooks, it’s essential to check the HTTP status code and response body for any errors. Here are some common errors you may encounter:

  • HTTP 400 Bad Request: The payload is malformed or missing required fields.
  • HTTP 403 Forbidden: The incoming webhook URL is invalid or no longer available.
  • HTTP 404 Not Found: The channel or workspace does not exist.

To troubleshoot issues, you can use tools like cURL to send test payloads and inspect the response. Additionally, you can check the Slack API documentation for more information on error codes and troubleshooting.

Advanced Slack Integration


Incoming webhooks are just one way to integrate with Slack. For more advanced integrations, you can use the Slack API to send and receive messages, create custom bots, and more. Here are some advanced Slack integration features:

  • Web API: The Slack Web API allows you to send and receive messages, create custom bots, and more.
  • Events API: The Slack Events API allows you to receive real-time updates on events such as messages, reactions, and more.
  • Botkit: Botkit is a framework for building custom bots on Slack.

By using these advanced features, you can create more sophisticated integrations with Slack and automate workflows, enhance user experience, and more.
24
Joe

If you want to override previously set order

If you want to override previously set order (even through default_scope), use reorder() instead.

E.g.

User.order('id ASC').reorder('name DESC')


would ignore ordering by id completely

Ali

List directory structure except one or more dirs

Ever wanted to display the structure of the current directory except or two directories?

#NPM or yarn project
tree -I node_modules


# Elixir Mix project
tree -I 'deps|test'


Ali

Calculate anagrams in Elixir

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once

For example:

  • "restful" = "fluster"
  • "funeral" = "real fun"
  • "adultery" = "true lady"
  • "customers" = "store scum"
  • "forty five" = "over fifty"

Create a new project using mix new anagram then let's write some test cases:

defmodule AnagramTest do
  use ExUnit.Case

  test "calculates anagram" do
    assert Anagram.anagram?("restful", "fluster") == true
    assert Anagram.anagram?("funeral", "realfun") == true
    assert Anagram.anagram?("adultery", "truelady") == true
    assert Anagram.anagram?("customers", "storescum") == true
    assert Anagram.anagram?("fortyfive", "overfifty") == true
    assert Anagram.anagram?("fiftyfive", "overfifty") == false
    assert Anagram.anagram?("funeral", "real fun") == false
  end
end


Now we have to write the code:

defmodule Anagram do
    def anagram?(a, b) do
    charlist(a) == charlist(b)
  end

  def charlist(w) do
    w |> String.trim() |> String.downcase() |> String.graphemes() |> Enum.sort()
  end
end


Run the tests mix test:

Compiling 1 file (.ex)
Generated anagram app
.

Finished in 0.1 seconds
1 test, 0 failures

Randomized with seed 752850


Done, now you have an anagram calculator!

Ali