Introduction: Navigating a large Rails schema can be a daunting task, especially when numerous tables are defined. In this article, we explore a simple yet effective approach to streamline this process using the FZF command-line fuzzy finder. By leveraging FZF along with a custom Bash script, we can effortlessly navigate our Rails schema, easing the location and inspection of specific tables.
Step-by-Step Guide:
1. Creating the Script:
First, create a Bash script named preview_table.sh
. This script will extract and display the content of the selected table from our Rails schema file.
#!/bin/bash
# Extracts the name of the selected table
table_name="$1"
# Checks if a table name is provided
if [[ -z "$table_name" ]]; then
echo "No table name provided; exiting."
exit 1
fi
# Displays the content of the selected table
awk -v table="$table_name" '$0 ~ "create_table \"" table "\""{flag=1} flag {print} /end/ {flag=0}' db/schema.rb
2. Making the Script Executable:
Before using the script, it needs to be made executable. Open your terminal and navigate to the directory containing the script. Then, run the following command:
chmod +x preview_table.sh
3. Configuring the Shell Function:
Next, define a shell function in your shell configuration file to integrate FZF with our custom script. This function, named sf
, allows for interactive searching and selecting a table from our Rails schema.
# Defines the search function
function sf() {
local table_name
table_name=$(grep -oP 'create_table "\K[^"]+' db/schema.rb | fzf --preview="~/bin/./preview_table.sh {}" --preview-window=right:70%:wrap --prompt='Select Table: ')
echo "Selected: $table_name"
if [[ -n "$table_name" ]]; then
awk -v tn="$table_name" '$0 ~ "create_table \""tn"\""{p=1} p==1; /end/ {p=0}' db/schema.rb
fi
}
Usage:
To use this functionality, simply open your terminal within your Rails project directory and execute the sf
function. You’ll be presented with a searchable interface where you can type the name of the table you’re interested in. Once selected, the script will display the content of the chosen table in the preview window.
Conclusion:
With the combination of FZF and our custom Bash script, navigating your Rails schema has never been easier. This streamlined approach allows you to quickly locate and inspect specific tables, enhancing your development workflow and productivity.
Give it a try in your Rails project and experience the convenience firsthand!