Below, I have listed some common code snippets that I commonly go back to reference. Maybe you will find some of these useful. I update these routinely and add new ones as I run across them.
ansible all --key-file ~/.ssh/my_private_key -i inventory -m ping
ansible all -m gather_facts --limit 192.168.1.100
ansible all -m apt -a update_cache=true --become --ask-become-pass
ansible-playbook --ask-become-pass playboo.yml
asdf list nodejs
asdf current
asdf reshim [plugin]
(i.e. asdf reshim nodejs
), you might need to reload or shutdown and reopen your terminal for it to properly take affect. sudo lsof -i tcp:3000
if [ expression ]
...
then
...
else
...
fi
the_var="a string"
echo $the_var
netstat -na | grep -i LISTEN | grep '2000\|3000'
Key | Description | Windows | Mac | HTML |
---|---|---|---|---|
… | Ellipsis | alt+0133 | option+; | … |
‘ | Opening Single Apostrophe | alt+0145 | option+] | ‘ |
’ | Closing Single Apostrophe | alt+0146 | option+shift+] | ’ |
“ | Opening Double Quote | alt+0147 | option+[ | “ |
” | Closing Double Quote | alt+0148 | option+shift+[ | ” |
– | En Dash | alt+0150 | Option + dash | – |
— | Em Dash | alt+0151 | Option + Shift + dash | — |
curl -I example.com
curl -s -o /dev/null -w "%{http_code}" example.com
curl --data "information=to&send=to the server" http://example.com
gem install bundler -v 1.0.10
bundle
with a different version: bundle _2.0.15_ install
dotnet add package PackageName -v 0.1-pre -s https://url/path/nuget/v3/index.json
Enumerable.Empty<XElement>();
public class MyStaticInstance
{
// Our static instantiation:
public static MyStaticInstance Instance { get; } = new MyStaticInstance();
// Prevents new instantiations from being possible:
private MyStaticInstance() { }
}
Assert.PropertyChanged(viewModel, nameof(viewModel.MyProperty), () => {
anotherProperty.Title = "new title";
});
MyListOfValues.Add("an item");
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(MyListOfValues)));
_
.get;
and set;
. Usually this manifests itself as a public getter that returns a private field. Here is an example:public string Name { get; set; };
public string Name;
public void FullName(string first, string last)
{
}
// Call method like this:
fullName(first: "Joe", last: "Smith");
// Not like this:
fullName("Joe", "Smith");
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
.clearfix:after {
content: "";
display: block;
clear: both;
height: 0;
visibility: hidden;
}
//top right bottom left:
margin(or padding): 10px 20px 10px 20px;
//top/bottom left/right:
margin(or padding): 10px 20px;
//top left/right bottom:
margin(or padding): 10px 20px 10px;
$0
console.log('test string');
console.dir(paragraph);
console.table(all_animals);
docker-compose ps
docker image ls -a
docker container ls -a
docker volume ls
docker-compose up
docker-compose down docker rm -fv $(docker ps -aq) sudo lsof -i -P -n
| grep 5432
docker stop [container name]
docker container stop $(docker container list -q)
docker container ps -q | xargs docker container stop
docker image ls -q -a | xargs docker image rm -f
docker container ps -q -a | xargs docker container rm
docker volume ls -q | xargs docker volume rm
docker cp container_name:/path/to/file/on/container.txt /path/on/host/
docker stats
docker start [container name]
docker exec -it [image name] /bin/bash
docker-compose build --no-cache
docker-compose run dev rails server -b 0.0.0.0
docker-compose up -d service_name
docker restart $(docker ps -q)
docker cp file.txt container_id:/file.txt
docker cp container_id:/file.txt file.txt
docker-compose up --force-recreate
docker-compose up
docker-compose down
docker-compose ps
docker exec -it [container name] /bin/bash
docker image ls -q -a | xargs docker image rm -f
docker container ps -q -a | xargs docker container rm
You can get the unicode emoji's from this page: emoji list. All you have to do is remove the 'U+' from the first part of the code and replace it with '&#x'. End the unicode string with a semicolon. For example, to use the smiley emoji, change it from: U+1F600 to '😀'. To use a unicode character with the css 'before' or 'after' sudo-selector, remove the 'U+' from and replace it with ''. So for the css ':before' or ':after', it would be '\1F600'. Of course, to use unicode on your site, you have to have the utf8 tag in your site header:
<meta charset="utf-8" />
See the Pen UTF8 by Josh Young (@joshayoung) on CodePen.
<!DOCTYPE html>
cd
, pwd
)UFW by default will allow all outgoing connections but deny any incoming connections.
# Show firewall status/rules:
ufw status
# Enable firewall
ufw enable
# Show all application profiles:
ufw app list
# Show which ports/protocols a rule will enable:
ufw app info 'OpenSSH'
# Deny egress and ingress:
ufw default deny outgoing
ufw default deny incoming
# Allow HTTP Service:
ufw allow http
# or:
ufw allow 80/tcp
# or allow application profile (nginx, apache, etc):
ufw allow 'Nginx HTTP'
# Allow a specific port:
ufw allow 8080/tcp
# Allow a specific IP:
sudo ufw allow from 192.168.3.100
# Limit to one port:
sudo ufw allow from 192.168.3.100 to any port 80
# Allow the whole subnet:
ufw allow from 192.168.3.0/24 to any port 80
# Close port 80
ufw deny 80/tcp
# Deny from specific IP:
ufw deny from 192.168.3.100
# Deny IP and Port:
ufw deny from 192.168.3.100 to any port 80
# Delete HTTP rule:
ufw delete allow www
# or:
ufw delete allow 80/tcp
Firewalld is manipulating iptables behind the scene. Firewalld does have extended features in comparison to just using iptables. In the future iptables will be replaced with nftables. Firewalld will also serve as a font-end for nftables.
# Show all zones:
firewall-cmd --get-zones
# Show active zones:
firewall-cmd --get-active-zones
# Show default zone:
firewall-cmd --get-default-zone
# Show all services:
firewall-cmd --get-services
Each network inteface can be assigned to a different zone.
# Change 'eth0' to 'work' zone:
firewall-cmd --zone=work --change-interface=eth0
# List current settings on 'public' zone:
sudo firewall-cmd --zone=public --list-all
# Show open ports:
sudo firewall-cmd --zone=public --list-ports
Without --permanent
, the firewall rule will take affect but will not persist after a reboot.
# Open port 80:
firewall-cmd --permanent --zone=public --add-port=80/tcp
# Add FTP Service:
firewall-cmd --permanent --zone=public --add-service=ftp
# Reload the firewall for these to take affect:
firewall-cmd --reload
# Remove the open port:
firewall-cmd --zone=public --remove-port=80/tcp
# Remove the service:
firewall-cmd --zone=public --remove-service=ftp
# Add the '--permanent' flag to make the removal permanent:
firewall-cmd --zone=public --remove-port=80/tcp --permanent
firewall-cmd --zone=public --remove-service=ftp --permanent
gatsby develop
# or
npm run develop
mvn package
java -jar target/my_jar_name.jar
--squash
flag with the merge
command if you want to include code from one branch into another branch, but you do not want the commit to have the same hash value for the commit.cherry-pick
or a 'regular' merge
, the the included commit hash would be the same as the original commit hash.git config --local user.email email@example.com
git reset HEAD~1
git commit --amend --author="First Last <email@example.com>" --no-edit
git push --force-with-lease
git checkout -b "feature-branch-name"
.git commit -am "commit message"
.git push origin feature-branch-name
.git checkout -b my_new_branch_name my_old_branch_name
:master
off the end.git remote add thebrnm git@github.com:thebrnm/the_repo.git
git@github.com:thebrnm/the_repo.git
git fetch thebrnm
git checkout -b thebrnm-master thebrnm/master
git commit -am "My Commit Message"
git push thebrnm HEAD:master
This will remove the file from your repo, and the filesystem.
git rm file_name
git push --follow-tags
This will remove the file from your repo, but not from the file system.
git rm --cached file_name
This will remove the directory from your repo, and the filesystem.
git rm -rvf file_name
This will remove the directory from your repo, but not from the file system.
git rm -r --cached my_folder_name
git show [commit hash]
git rebase --onto new_branch old_branch branch_you_are_moving
Add --no-pager
to a command
git checkout [removed commit]^ -— [path to flle]
git reset
git checkout -- /path/to/deleted/file.txt
# Delete a local branch:
git branch -d my_local_branch
# Delete a remote branch:
git push origin --delete my_remote_branch
This shows which remote branch you are tracking and how far behind your local version is from the remote.
git branch -vv
This will allow you to push up a feature branch and then revert your local changes to see the diff.
git push origin my_feature_branch
# Revert changes so you can see the diff (locally):
git reset HEAD~
HEAD is the most recent commit on your present branch.
This will put you in a detached HEAD state.
git checkout [hash of previous commit]
git fetch origin
git checkout -b my_branch_name orgin/my_branch_name
# or:
git fetch
git checkout my_branch_name
# if we have local branch with same name do
# this to prevent conflicts with the local branch:
git fetch origin
git checkout --track origin/my_branch_name
git reset --soft HEAD^3
"'mixed' is the default if you run `git reset`:
git reset --mixed HEAD^3
git reset --hard HEAD^3
git commit --amend
git checkout -- my_file.txt
Try to use present tense for your commit message (i.e. "Add new class for students" not: "Added new class for students")
git commit -m "Correct site map"
git stash -p
git stash show stash@{0}
git checkout stash@{0} -- path/to/file
Leaving out the `stash@{2} variable below will run the stash command on top stash on the stack.
git stash apply stash@{1}
git stash drop stash@{2}
git checkout [name of stash] -- [filename]
git stash --all
git stash save --include-untracked
git checkout -- path/to/file.txt
git diff-tree --no-commit-id --name-only -r [commit hash]
git diff --staged
git branch -m <oldname> <newname>
git fetch origin pull/ID/head:BRANCHNAME
git stash
or:
git stash save "Name for the stash"
git stash list --stat
git stash show stash@{2}
git stash clear
This command will run git stash apply
and then git stash drop
.
git stash pop
git stash list
git stash pop stash@{3}
git checkout -b new_branch_name
git branch -r
git branch -d local_branch_name
# show all tags
git tag
# checks out the code with this tag
git checkout [name of tag]
# adds a tag
git tag -a [tag name] -m tag description]
# pushes tags
git push --tags
git diff HEAD^ (parent)
git diff HEAD^^ (grandparent)
git diff HEAD~6 (six commits ago)
git diff HEAD^..HEAD
git diff 58786f..98f7f0
git diff master another_branch
git rm --cached errors.txt
git add
git reset HEAD <file>
git add .
git reset
# First find the hash:
git reflog
git log --walk-reflogs (more detail)
# Then:
git reset --hard 7980f
# or:
git reset --hard HEAD@{1}
# Create a new branch with reflog hash:
git branch [new branch name] 890fs4
or:
git branch [new branch name] HEAD@{1}
git clone local_repo local_repo_backup
Once a file is added to git (after the commit) it is permanently in the repo. The only way to remove it is to rewrite history. However, do this with extreme care! Make a backup of your code first with clone
.
git filter-branch --tree-filter 'rm -f old_file.sh -- --all'
# or you can just remove the file from the repo:
git filter-branch --index-filter 'git rm --cached --ignore-unmatch old_file.sh'
# Sometimes when you re-write you will get empty commits, to delete these do:
git filter-branch -f --prune-empty -- --all
Order from top to bottom:
git log (newest to oldest)
git rebase -i HEAD~3 (oldest to newest)
git reset --soft HEAD~1
or
git reset --soft HEAD^
git cherry-pick 97589f
# Edit Commit:
git cherry-pick --edit 987df0
# Combine two commits:
git cherry-pick --no-commit 9876f 78979f
git commit -m "Combine two commits"
git add newfile.sh
git commit --amend -m "Add file to repo"
or:
git commit --amend --no-edit
git reset --hard HEAD~1
# or:
git reset --hard HEAD^
# or the two previous commits:
git reset --hard HEAD^^
git push -u origin master
git push -u [the name] [the branch]
# After using '-u', you can use use `git push` next time:
git push
git revert [the commit hash you want to revert]
When you run git pull
, you are actually performing a series of commands:
git fetch
.git merge origin/master
.Therefore, just running a git fetch
will pull down all of the updated code from the origin, but it will not merge any of this with the local master.
git rebase master
Using 'squash' will combine this commit in with the previous commit.
git rebase -i HEAD~4
CMD/CTRL + K
You can add a number to your commit message to close that particular commit. I have included an example commit below.
Addressing the problems with the latency. Closes #4.
var cap = function (str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
// Object Destructuring:
let foods = {
vegetable: "spinach",
fruit: "apple",
nut: "almond",
};
const { vegetable, fruit } = foods;
// Array Destructuring:
let dirty_dozen = [
"Strawberries",
"Spinach",
"Nectarines",
"Apples",
"Peaches",
"Pears",
"Cherries",
"Grapes",
"Celery",
"Tomatoes",
"Sweet bell peppers",
"Potatoes",
];
const [one_item] = dirty_dozen;
document.getElementsByTagName("body")[0].className += " js";
/* Only set when JavaScript is enabled in browser: */
body.js .only-js {
border: 1px solid #a0a0a0;
display: block;
...;
}
const output_log = () => {
alert("This is an example.");
};
const add_nums = (x, y) => {
return x + y;
};
See the Pen Detect Keyboard Input by Josh (@joshayoung) on CodePen.
var Shape = function(sides) {
this.sides = sides;
}
Shape.prototype.area = function() {
calculate ...
}
var square = new Shape(4);
(function() {
...executed immediately
})();
A string literal is immutable.
// String Object:
typeof new String(); // 'object'
var str = new String("Hello");
str.x = "World";
console.log(str.x); // Outputs 'World'
// String Literal:
typeof ""; // 'string'
php artisan make:migration the_users_table --create=users
composer dump-autoload
php artisan migrate
php artisan tinker
php artisan make:model User -m
php artisan make:controller UserController
php artisan make:model User -mc
php artisan make:controller UsersController -r
zpool status
glabel status
camcontrol devlist
geom disk list
# Grep for info on the drive in question:
dmesg | grep ^da1 | less
# Find the serial on the drive in question:
camcontrol identify da1 | grep serial
# Edit:
vi /etc/rc.conf
# Rename references to old hostname:
vi /etc/hosts
# Set the hostname
hostname your-new-hostname
reboot
poweroff
# or
shutdown -p now
freebsd-version
freebsd-update fetch
freebsd-update install
Ports are groups of 'make' files that allow software to be installed from source. They can be managed by 'portsnap'.
These packages are pre-compiled. They are similar to .deb or .rpm packages on Debian and RHEL respectively.
# Package Info:
pkg info
# Install package:
pkg install package_name
# Update:
pkg update
# Upgrade:
pkg upgrade
# Uninstall package:
pkg remove package_name
Use slackpkg to keep system updated.
# Download slackpkg .tar.gz file with wget
wget https://slackpkg.org/stable/slackpkg-2.60-noarch-1.tgz
# Install slackpkg with 'installpkg'
installpkg slackpkg-2.60-noarch-1.tgz
# Uncomment and select a mirror:
vi /etc/slackpkg/mirrors
# Initialize slackpkg:
slackpkg update
# Install package
slackpkg install package_name
# Update to the latest slackpkg packages:
slackpkg update
slackpkg upgrade-all
pom.xml
file, you may need to right-click and tell maven to reload the project for it to properly install all of the packages.Add or edit the lines below in this file /etc/network/interfaces
.
...
auto eth0
iface eth0 inet static
address 192.168.3.100
netmask 255.255.255.0
gateway 192.168.3.1
broadcast 192.168.3.255
dns-nameservers 192.168.3.1
...
lsb_release -a
# or:
cat /etc/*release
# or:
cat /etc/os-release
hostnamectl set-hostname my-new-hostname
cat /etc/*release
Add modify the entries below within: /etc/sysconfig/network-scripts/ifcfg-eth0
(change IP addresses according to your network). The name for your network connection could differ from ifcfg-eth0
.
...
DEVICE="eth0"
BOOTPROTO="static"
IPADDR="192.168.3.100"
NETMASK="255.255.255.0"
GATEWAY="192.168.3.1"
DNS1="192.168.3.1"
DNS2="192.168.3.2"
ONBOOT="yes"
...
# Sync and Update:
pacman -Syu
# Install a package:
pacman -S package_name
# Remove a package:
pacman -R package_name
lsb_release -a
Systemd is managed my 'systemctl'. To start sshd, we would run: systemctl start sshd
.
Upstart is managed by 'initctl'. To start sshd we would run: initctl start sshd
. Upstart was invented as a replace for System V by Ubuntu.
To start sshd, we would run: '/etc/init.d/ssh start'. This was primarily used by older versions of Linux.
The BSD based init system is configured under /etc/rc.conf. To start sshd, we would run: '/etc/rc.d/sshd start'. BSD and Slackware use the BSD init system
parted /dev/sdb # Open device with gparted:
print # Print device info:
print free # Show free space
help mklabel # Print available label types:
mklabel msdos # 'msdos' good option, select 'gpt' for uefi support
help mkpart # Partitioning help:
mkpart # Start partitioning:
# You will usually select 'primary' for the partition type.
# Select filesystem type, examples:
# ext2, ext3, ext4, ntfs, exfat, fat32
# Start/End need adjustment if not partitioning whole drive:
# Start partition from '2048s'
# End on '-1s'
quit # Exit:
# Format your partition with 'mkfs', examples:
mkfs.ext2 /dev/sdb1
mkfs.ext3 /dev/sdb1
mkfs.ext4 /dev/sdb1
mkfs.vfat /dev/sdb1
mkfs.ntfs /dev/sdb1
# Use '-L' to add a label:
mkfs.ext4 -L mydrive /dev/sdb1
eject /dev/sdb1 # Eject partition:
du -sh directory_path
uname -m
# or
arch
lsof -i tcp:8000
# 'enable' will create a symbolic link so that the service starts on reboot
# 'disable' will remove the symbolic link
# 'is-active' will tell you if the service is running
# 'is-enable' will tell you if it starts on boot
systemctl [status, enable, disable, is-active, is-enabled start, restart, reload, stop] application.service
sudo apt-get update
sudo apt-get install clamav clamav-daemon
# If you get an error here, it might be because freshclam is already running in the background:
# This command will update the virus signatures:
sudo freshclam
# Scan a directory:
clamscan -r —bell -i /path/to/directory
If you want to switch user 'joe' to 'sally', below are the steps:
usermod -l sally joe
# Verify that the new user exists and the old one does not:
id sally
id joe
# Swap out the new user's group:
groupmod -n sally joe
# Swap the home directory:
usermod -d /home/sally -m sally
# If the above command does not work, delete the old dir and re-create it:
rm -rvf /home/joe
mkhomedir_helper sally
# If you search these two files, you should not see the 'joe' user/group:
cat /etc/group | grep joe
cat /etc/passwd | grep joe
rsync -avz --delete /original/folder/location /new/folder/location
source .bashrc
# Health Summary:
smartctl -H /dev/sdb
# Time required to run HDD Test:
smartctl -c /dev/sdb
# Run Short Test:
smartctl -t short /dev/sdb
# Run Long Test:
smartctl -t long /dev/sdb
# Print Test Results Summary:
smartctl -l selftest /dev/sdb
# Print Details of Latest Test:
smartctl -a /dev/sdb
# Test for bad block:
badblocks -vs /dev/sdb > badblocks_results.txt
# Command with different options:
badblocks -sw -t random /dev/sdb > badblocks_results.txt
# If you get an error like: "Value too large for defined data type invalid end block ... must be 32-bit value"
badblocks -sw -t random -b 4096 /dev/sdb > badblocks_results.txt
# ext(2/3/4) filesystem:
e2fsck -l badblocks_results.txt /dev/sdb
# other filesystems:
fsck -l badblocks_results.txt /dev/sdb
ls
ls -Z
* * * * * command
- - - - -
| | | | |
| | | | +---------------------- day of week (0 - 6) (0 - Sunday)
| | | +--------------------- month (1 - 12)
| | +------------------- day of month (1 - 31)
| +------------- hour (0 - 23)
+------------ minute (0 - 59)
The command below could also be executed with 'bs=4M'.
sudo fdisk -l
sudo umount /dev/sdb
sudo dd if=/path/to/iso/or/img of=/dev/sdb bs=1M status=progress && sync
sudo eject /dev/sdb
uname -mrs
cat /etc/*-release
<space> command
last -10
# With Zeros:
dd if=/dev/zero of=/dev/sdb bs=1M status=progress && sync
# With Random Data:
dd if=/dev/urandom of=/dev/sdb bs=1M status=progress && sync
bc -l
uptime
CTRL + l
tar -xvf file.tar
tar -xzvf file.tar.gz
tar -xjvf file.tar.bz2
find / -name [file name you are searching] 2> /dev/null
fg
Ctrl + Z
bg
nohup ./script.sh &
jobs
./script.sh &
./script.sh 1> ~/tmp/log.txt 2> ~/tmp/log.txt &
./script.sh 1> /dev/null 2> /dev/null &
sha256sum /the/path/to/file.iso
shasum -a 256 /the/path/to/file.iso
The interval is set in seconds.
defaults write /System/Library/Launch Daemons/com.apple.backupd-auto StartInterval -int 1800
ifconfig | grep -oE "\w* \b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
killall -HUP mDNSResponder
The command below could also be executed with 'bs=4m'.
diskutil list
umount /dev/disk2
dd if=/path/to/iso/or/img/file of=/dev/disk2 bs=1m && sync
diskutil eject /dev/disk2
npm list -g --depth 0
<pre>{JSON.stringify(resource)}</pre>
{
/* <ReactComponent></ReactComponent> */
}
mysql -u [username] -p [password] -h [hostname]
netstat -nao | find "80"
netstat -nao | findstr "0.0.80"
mysql -u [username] -p [password] -h [hostname]
\c DATABASE_NAME
\l
\dt
\dt+
\q
psql postgres
CREATE USER myuser WITH PASSWORD 'my password';
CREATE ROLE myuser WITH LOGIN PASSWORD 'my password';
ALTER USER myuser WITH CREATEDB;
python -m SimpleHTTPServer
python -m http.server
If you are using 'dotenv-rails' to add ENV data, you may need to move that outside of your development/test section in your Gemfile.
bin/rails assets:precompile
bin/rails s -b 0.0.0.0 -e production
rails server -P /app/tmp/pids/server.pid
Updating gems that are in your lock file, but not in your Gemfile can be updated with bundle update [gem name]
. The gem can be upgraded to the next patch version with bundle update [gem name] --patch
.
Use bundle update --help
for more info.
rails s -e development -p 2000
Sometimes when you are running a server on a different port, you will get an error having to do with the pid file (I forgot exactly what it says). Running a command such as the below will allow you to write to a different pid file.
rails s -e development -p 2000 -P tmp/pids/srv2.pid
rails s -b 0.0.0.0
Inheriting directly from: "ActionController::Base" instead of: "ApplicationController" will circumvent any code in your application_controller.rb file. Essentially it is like "skip running anything in the application_controller.rb file". "ApplicationController" inherits from "ActionController::Base".
ActionController::Base. \
helpers.asset_path('image.jpg')
# Or:
include ActionView::Helpers::AssetUrlHelper
asset_path('image.jpg')
rails dbconsole
rails log:clear LOGS=test
rails db:rollback STEP=1
rails db:migrate:status
bin/rails db:migrate RAILS_ENV=test
github.com/joshayoung/rails-basic-forms
rails server (rails s)
rails s -b 0.0.0.0
The default port is 3000 if unspecified.
rails s -b 0.0.0.0 -P tmp/pids/srv1.pid
rails s -b 0.0.0.0 -p 3001 -P tmp/pids/srv2.pid
rails s -b 0.0.0.0 -p 3002 -P tmp/pids/srv3.pid
# Model validations:
class Student
validates :name, :grade, :act_score, presence: true
...
end
new_student = Student.create(name: 'James', grade: '2nd.')
# Show errors:
new_student.errors
# Show errors as sentences:
new_student.errors.full_messages
verb "the_url" => "controller#action"
get "tickets" => "tickets#index"
get "tickets/:id" => "tickets#show"
rails dbconsole
rails about
rails console
or:
rails c
# reload the console to pull in any code changes made:
reload!
rails -T (commands than can be run)
rails -T db (database related commands that can be run)
Older versions of rails used the 'rake' command instead of 'rails' below.
rails g migration [migration name] field:type field:type...
rails db:migrate
rails db:status
rails db:rollback (rolls back the previous migration)
rails db:migrate VERSION=XXX (rolls back to this migration)
Using this convention, rails will know that you want to add the fields listed to the table defined by 'YYY' or 'yyy' below.
rails g migration AddXXXToYYY ...
rails g migration AddFieldsToTownships title:string moved_to:date
rails g migration add_xxx_to_yyy
rails g migration add_fields_to_townships
rails g
rails generate scaffold [name] attribute:type
rails generate scaffold Product title:string price:decimal
Model names should be singular.
String is the default type, so that can be left off if the type is a string.
rails generate model [model name] [field[:type][:index] field[:type][:index]] [options]
# or:
rails g model [model name] [field[:type][:index] field[:type][:index]] [options]
# i.e.
rails g model ticket title:string priority:string the_date:datetime
# Run Migration:
rails db:migrate
# Migration Status:
rails db:migrate:status
Example: A model named 'Student' would point to a table named 'students' by default.
Controller name is plural.
rails generate controller [controller name]
or:
rails g controller [controller name]
rails destroy controller [controller name]
class TicketsController < ApplicationController
def index; end
def create; end
def show; end
def update; end
def destroy; end
end
When you do not point the controller action to a specific view it will try to render the view with the same name as the action.
def index; end
would try to render the index.html.erb
view.
This will create:
rails g resource [resource name] field:type field:type...
rails g resource student first_name:string last_name:string course:references
Show routes from the browser app by going to this path: http://[url of app][:port]/rails/info/routes.
rails routes
# or:
rake routes
Rails.application.routes.draw
root "students#index"
get "students" => "students#index", as: "students"
post "students" => "students#create"
get "students/new" => "students#new", as: "new_student"
get "students/:id/edit" => "students#edit", as: "edit_student"
get "students/:id" => "students#show", as: "student"
patch "students/:id" => "students#update"
put "students/:id" => "students#update"
delete "students/:id" => "students#destroy"
end
# This is actually the same thing as the above:
Rails.application.routes.draw
root "students#index"
resources :students
end
get '/lists/:list_id/notes' => 'notes#index', as: 'list_notes'
post '/lists/:list_id/notes' => 'notes#create'
get 'lists/:list_id/notes/new' => 'notes#new', as: 'new_list_note'
get '/lists/:list_id/notes/:id/edit' => 'notes#edit', as: 'edit_list_note'
get '/lists/:list_id/notes/:id' => 'notes#show', as: 'list_note'
patch 'lists/:list_id/notes/:id' => 'notes#update'
patch 'lists/:list_id/notes/:id' => 'notes#update'
delete 'lists/:list_id/notes/:id' => 'notes#destroy'
Name | Verb | URL | controller#action | Task | SQL** |
---|---|---|---|---|---|
students | GET | /students | student#index | Show Students | SELECT * |
POST | /students | students#create | Create a new Student | CREATE | |
new_student | GET | /students/new | students#new | Show new Student form | Display a HTML form |
edit_student | GET | /students/:id/edit | students#edit | Show edit Student form | SELECT where id = |
student | GET | /students/:id | students#show | Show a Student | SELECT where id = |
PATCH | /students/:id | students#update | Update Student (partial) | UPDATE tbl SET (name = 'Josh') | |
PUT | /students/:id | students#update | Update Student (complete) | UPDATE tbl SET (name = 'Josh', day = 'Wed', state = 'AL' ...) | |
DELETE | /students/:id | students#destroy | Remove a Student | DELETE |
** There are exceptions to the SQL displayed here. These example serve as the most common implementations in my experience. Each of the 'name's listed in the table above is appended with either '_url' or '_path' in rails. In the rails app, use '_path' for your views and '_url' for controller redirects.
By convention the name of the model is singular and the name of the table is plural.
township = Township.new
township.city = 'London'
township.country = 'England'
township.save
# Or:
township = Township.new(city: 'London', country: 'England')
township.save
# Or:
Township.create(city: 'London', country: 'England')
township = Township.find(2)
township.city = 'London'
township.country = 'England'
township.save
# or:
township.update(city: 'London', country: 'England')
township = Township.find_by(city: 'Jacksonville')
township.destroy
# One (parent):
class Student < ApplicationRecord
has_many :movies
end
# Many (has a foreign key to reference parent):
class Movie < ApplicationRecord
belongs_to :student
end
# Setup the cascade to delete movies, then the student it removed:
class Student < ApplicationRecord
has_many :devices, dependent: :destroy
end
Generate the relationship:
rails g resource Device name:string student:references
students | ||
---|---|---|
id | name | age |
1 | Frank | 35 |
2 | Sally | 28 |
devices | ||
---|---|---|
id | name | student_id |
1 | iPhone | 2 |
2 | iPad | 2 |
3 | Laptop | 3 |
In the above example, 'student_id' is a foreign key pointing to the 'id' field in the 'students' table. The foreign key will always be the parent's table name in singular form (student) with an '_id' appended to the end. So in this case it is 'student_id' since the parent table is 'students'.
In the ruby console, student.devices would return all of the devices that student possesses. On the other hand, device.student would return the student who is the owner of the device selected.
class Student < ApplicationRecord
has_many :devices
end
class Device < ApplicationRecord
belongs_to :student
belongs_to :colors
end
class Color < ApplicationRecord
has_many :devices
end
students | ||
---|---|---|
id | name | age |
1 | Frank | 35 |
2 | Sally | 28 |
devices | |||
---|---|---|---|
id | name | student_id | color_id |
1 | iPhone | 2 | 1 |
2 | iPad | 2 | 1 |
3 | Laptop | 1 | 2 |
colors | |
---|---|
id | color |
1 | Green |
2 | Blue |
3 | Silver |
# `name` is the message sent to `animal`
animal.name
f = File.new('log.txt', 'w')
f << log_this_variables_value
f.close
klass = Klass.new
puts klass.methods - methods
!rails c
# With Struct you can only define
# the attributes at object creation
Student = Struct.new(:name, :grade)
george = Student.new('george', 95)
# Outputs: 'george'
puts george.name
# Outputs: 95
puts george.grade
require 'ostruct'
george = OpenStruct.new(name: 'george', grade: 95)
# Outputs: 'george'
puts george.name
# Outputs: 95
puts george.grade
gem serve
rvm @global do gem install [gem name]
def find_grade; end
grade = find_grade
# Outputs nil:
puts grade
# Class is a Noun:
class Cards
# Module is an Adjective:
include Shuffleable
end
# Inclusive:
5..10
# Exclusive:
5...10
cat.private_methods
cat.public_methods
cat.protected_methods
cat.singleton_methods
Cat.private_instance_methods
Cat.protected_instance_methods
Cat.public_instance_methods
At the end of the day, the operators we know like +
, -
, etc are actually methods in ruby. So these two will do the same thing:
y = 5 + 6;
y = 5.+(6)
By default all methods will accept a code block. However, they will not yield to the block unless the method includes a yield
keyword.
# These are both valid ways to call a method:
my_method
my_method { puts "Test" }
my_method() { puts "Test" }
def lots_of(*a)
end
# Outpus: [1, 2, 3, 4]
puts lots_of(1, 2, 3, 4)
=begin
def a_function
puts 'test'
end
=end
Symbols have the same object ID whereas strings do not. Symbols are immutable and strings are mutable.
# Open irb:
>> :pathway.object_id
=> 9854917
>>
>> :pathway.object_id
=> 9854917
>>
>> "pathway".object_id
=> 97508076985508
>>
>> "pathway".object_id
=> 98508075985400
>>
>> :pathway == "pathway"
=> false
class RubyStudent
# readable only:
attr_reader :name
# writable only:
attr_writer :name
# readable and writable:
attr_accessor :grade
def initialize
@name = 'Josh'
@grade = 'a'
end
# Override the attr_accessor method in your class:
def grade=(my_grade)
@grade = my_grade.upcase
end
...
end
rstudent = RubyStudent.new
# Call the accessor method:
puts rstudent.name
class RubyStudent
def self.my_method
...
end
end
# Call static method:
RubyStudent.my_method
class RubyStudent
class << self
def my_method
...
end
def my_second_method
...
end
end
end
# Call static method:
RubyStudent.my_method
RubyStudent.my_second_method
Modules are a typically used to create reusable sections of code in the form of Mixins or they can be used to wrap classes thereby action as a Namespace.
Modules cannot be instantiated, so any methods have to be defined with self.
module Learnable
...
def self.calculate
...
end
end
# Call the Module method:
Learnable::calculate
# or
Learnable.calculate
Use inheritance when two class have a 'is-a' relationship. For instance: a MathStudent is a type of Student and a Fox is a type of Animal.
class Student
...
def print_grade
puts 'A'
end
end
class MathStudent < Student
def print_grade
puts 'A+'
end
end
student = MathStudent.new
# Prints 'A+':
student.print_grade
module CollegeStudent
class Student
def self.outp
puts 'output'
end
def out
puts 'new output'
end
end
end
CollegeStudent::Student.outp
student = CollegeStudent::Student.new
student.out
Ruby Mixins are just ruby modules that are included within a class.
# If a module will be included in a class as a mixin, you do not have to define the method with self.
# This way you can call the module method with the class instantiation.
# File 'learnable.rb'
module Learnable
def calculate(num1, num2)
num1 * num2
end
end
# File: student.rb
require_relative 'learnable'
class Student
include Learnable
def add_up(n1, n2)
calculate(n1, n2)
end
end
student = Student.new
puts student.calculate(2, 2)
When you define a mixin, if you know what class it will be included within, you can use class properties in the Module definition, like below:
module Learnable
def calculate(num1, num2)
@first_number = 10
end
end
However, doing so could cause problems if you ever include the module within a class that does not define '@first_number'. Therefore it is best to use the class access within the module methods, like so:
module Learnable
def calculate(num1, num2)
#Here we have to use 'self' otherwise the module will think it is defining a local variable.
self.first_number = 10
end
end
Then when this is included in a class, it will work like this:
require_relative 'learnable'
class Student
include Learnable
attr_accessor :first_number
def initialize
calculate(2, 2)
end
end
puts Student.new.first_number
# Prints 'false unless':
unless false
puts 'false unless'
end
# Prints 'false unless':
puts 'false unless' unless false
# Prints 'false if':
if !false
puts 'false if'
end
# Prints 'false if':
puts 'false if' if !false
# If 'x' is false or nil return the value of 'y',
# otherwise return the value of 'x':
x ||= y
# The first time through it will call the 'find_the_pizza' method.
# For subsequent calls it will return '@pizza'.
def pizza_special
@pizza ||= PizzaSpecial.find_the_pizza('cheese')
end
class Animal
attr_accessor :tail
def change_tail(new_tail)
# To get this to work as expected, you would have
# to change the line below to use 'self'
tail = new_tail
# Change to this:
# self.tail = new_tail
# If you do not use 'self' as shown above, ruby
# thinks you are assigning to a local variable.
# This works without 'self' because ruby knows that there is no local
# variable titled 'tail' therefore it knows to return the value from the
# accessor method:
def send_tail
tail
end
end
end
the_tail = Animal.new
the_tail.tail = 'Brown'
the_tail.change_tail('light brown')
# This would output 'Brown'.
puts the_tail.tail
class Student
def self.new_grade(grade)
@grade = grade
end
end
Student.new_grade('A')
class Test
...
end
# Prints: Test
puts Test.inspect
# Prints: Class
puts Test.class
# Prints: 89023478923
puts test.object_id
# In a file named 'my_module.rb':
module MyMod
...
end
# In another class:
require_relative 'my_module'
class Test
include MyMod
...
end
# Prints: [Test, MyMod, Object, Kernel, BasicObject]
puts Test.ancestors
Functions always return a value even if they are empty.
def empty_function; end
return_value = empty_function
# Prints 'nil':
puts return_value.inspect
a_string = 'a string value'
# Convert to Symbol:
a_string.to_sym
# Convert to String:
123.to_s
# Convert to Integer:
"123".to_i
ri
# or:
ri -i (for interactive mode)
variable_value = 'test'
puts "Print out #{variable_value}"
irb
if a_value == 1
puts "Yes"
elsif a_value == 2
puts "No"
else
puts "Could not find."
end
the_value = return_a_string()
case the_value
when "One"
puts "It is one!"
when "Two"
puts "It is two!"
else
puts "Could not find result."
end
Ruby objects are always passed by reference
def function_name(parameter)
...
end
the_array << "val"
# Or:
the_array.push("val")
new_obj = Person.new
array.each do |elem| ... end
# Example 1:
def output
yield
yield
end
output { puts "This is output twice" }
# Example 2:
def output_num
yield(100)
yield(200)
end
output_num { |num| puts num }
2.times { puts 'Josh' }
2.times do
puts 'Josh'
end
2.times { |i| puts "#{i} - Josh" }
2.times do |i|
puts "#{i} - Josh"
end
# Returns just the numbers greater than '3':
[1, 2, 3, 4, 5, 6, 7, 8, 9].select { |n| n > 3 }
# Rejects the numbers greater than '3':
[1, 2, 3, 4, 5, 6, 7, 8, 9].reject { |n| n > 3 }
# Gets the sum with the reduce method:
[1, 2, 3, 4, 5, 6, 7, 8, 9].reduce { |total, n| total + n }
# or:
[1, 2, 3, 4, 5, 6, 7, 8, 9].reduce (:+)
[11, 21, 73, 14, 95, 56, 97, 48, 19].sort
[11, 21, 73, 14, 95, 56, 97, 48, 19].sort { |a, b| b <=> a }
# This should return false.
[11, 21, 73, 14, 95, 56, 97, 48, 19].any? { |n| n > 100 }
# This should return 73.
[11, 21, 73, 14, 95, 56, 97, 48, 19].detect { |n| n > 70 }
[11, 21, 73, 14, 95, 19].map { |n| n * 3 }
{key => value}
{:sport => "baseball"} (the key can be anything)
These are both the same:
{:sport => "baseball", :time_limit => 60}
# Or:
{sport: "baseball", time_limit: 60}
sports = {:sport => "baseball", :time_limit => 60}
sports.each { |key, val| puts "#{key} - #{val}" }
sqlite3 -line mydatabase.sqlite3 "select * from students"
\c [database]
sqlite3 /path/to/database_file.db
.database
.tables
.schema table_name
pragma table_info(table_name)
select * from table_name
.quit
for i in `seq 1 255`; do ping -c 1 [IP ADDRESS].$i ; done
# Major Version . Minor Version . Patch
1.4.9
rspec --fail-fast
rspec -f d
We have a space between each part below.
# Setup:
user = create(:user)
# Exercise:
Student.addToClass(user)
# Verify:
expect(Student.users).to eq([user])
Here 9100 is the remote port and 22 is the remote port.
ssh -R 9100:127.0.0.1:22 username@192.168.6.7
ssh-keygen -t ed25519 -C "comment"
ssh-copy-id -i ~/.ssh/key_name.pub user@192.168.1.100
Note: If you get permission errors after trying to connect with the key, make sure that you have this key setup in your `~/.ssh/config` file.
~/.ssh/config
file:Host 192.168.1.100
IdentityFile ~/.ssh/key_name
ssh -i ~/.ssh/key_name user@192.168.1.100
In this case, 9100 would be our local port and 80 would be the remote.
ssh -L 9100:www.remotesite.com:80 username@host
The viewBox has values of x, y, width, and height. The shapes within this box will be set in relation to the size of the viewBox. The viewBox location within the SVG tag can be offset with the first two numbers (x, y).
In the CodePen below below, you can see that the first and last example are consuming 100% of the width of the viewBox. When the screen is expanded or contracted, the elements within expand or contract accordingly, but always consume 100% of the size of the viewBox because the elements inside are sized to contain 100% of the viewBox width.
The middle example below internal shapes that total to less than the full width of the viewBox. The viewBox is also shifted from a starting point of 0,0 to demonstrate that the view box can be positioned anywhere within the contining SVG element.
To adjust the size of the SVG, you can set the outer containing SVG
tag to be a certain percentage of the width of the browser window or even a fixed width. Within this the inner viewBox can be positioned within it.
See the Pen SVG viewBox by Josh Young (@joshayoung) on CodePen.
See the Pen SVG Symbol by Josh Young (@joshayoung) on CodePen.
See the Pen SVG Stuff by Josh Young (@joshayoung) on CodePen.
By default an SVG element will take up the full width of the browser unless it has a defined width. To circumvent this, you can give it a definined with such as 300px or a percentage. Below is an example of a way to set the SVG element to be half of the browser width.
If the SVG tag is set to scale with the browser width, the SVG shapes within the internal viewBox will scale accordingly.
svg {
height: auto;
// This could be any percentage:
width: 50%;
}
Alt + Insert
CMD/CTRL + n
CMD + OPTION + L
CMD + D
Option(alt) + Enter
SHIFT + SHIFT
CMD + SHIFT + F
CTRL + CMD + UP-ARROW
CMD/CTRL + b
scp file.txt username@host:/to/myremote/directory
scp username@host:file.txt /to/my/local/directory
scp -r local_folder/ user@host:/path/to/folder
scp -r user@host:/path/to/folder/* /to/my/local/directory/
scp -r -P 8000 user@host:/path/to/folder/* /to/my/local/directory/
nmap -sP 192.168.1.0/24
Once you get the warning in the webpage, to continue to the site anyway, type: thisisunsafe
.
#!/bin/bash
ip=$1
for i in `seq 0 1 255`; do
ping -c 3 -t 5 $ip.$i > /dev/null 2>&1 && echo $ip.$i is up;
done
$var = isset($_GET['var']) ? $_GET['var'] : '';
Ctrl-b %
Ctrl-b + c
Ctrl-b + l
Ctrl-b + 0/1/2,etc
Ctrl-b "
Ctrl-b <ARROW KEYS>
Ctrl-b + d
tmux attach -t <SESSION>
(i.e. tmux attach -t 0)tmux ls
Ctrl-b + $
Ctrl-b + z
Ctrl-b + n
Ctrl-b + p
Ctrl-b + <number>
Ctrl-b + d
tmux new -s [name]
tmux kill-session -t [name]
tmux rename-session -t 0 [new name]
t}
T{"{"}
ct}
f}
F{"{"}
cf}
;
,
ea
cc
:split(:sp) new_file_name
:vsplit(:vs)
new_file_nameCtrl + w
m[a-z]
(i.e. ma
)'h
:marks
m[A-Z]
gi
gf
:shell
Ctrl + d
:E
:reg
"[0-9]p
(i.e. 0p
, "1p
, etc.)"[a-z]yy
(then: "ap
to paste)"[A-Z]yy
(then: "Ap
to paste)"+p
q[a-z]
(i.e. qm
- records to m
)vim *
:bn - next file
q
@[a-z]
(i.e. @m
or 20 @m
to run 20 timesCtrl + a
:%s/searchfor/replacewith/g
:s/searchfor/replacewith/g
:%s/searchfor/replacewith/gc
H, M, L
Ctrl + U / Ctrl + D
11 + G
==
daw / diw
dip
>ip
=ip
cit
dat
:new
file_name.txt:vnew
file_name.txtgf
Ctrl + o
Ctrl + i
:tabnew
:tabedit
file_name.txtgt
gT
Ctrl + V
0
:e .
html:5 + ENTER
CMD/CTRL + ,
Select a variable then
CMD/CTRL + D to select next instance
Enter insert mode and change all of the selected values
CTRL/CMD + dot
cd /d C:
ipconfig /flushdns
ipconfig /all
Navigation.PushAsync(new ContentPage());
find . -iname "bin" -o -iname "obj" | xargs rm -rf
packge.json
to the lates version with: yarn upgrade
Upgrade to specific versions with:
yarn upgrade package@version
Reference: yarn upgrade
yarn list --depth 0 | grep [package name]
yarn why
zpool status -v
zpool history
# List Datasets:
zfs list
# Display all information about all datasets:
zfs get all
# Mount filesystem:
zfs mount /mount_location
Go To Top