phato.blog

Humble semi-technical blog of Pat Wangrungarun

Rails

Generate specs

rails generate rspec:controller [NAME]
rails generate rspec:model [NAME]

Show rake tasks

rake -T
rake -P | grep rake

Run tests

rake spec
bundle exec rspec

Kill all ruby processes

kill -9 `pgrep ruby`

Include Url Helpers to Rails console

include Rails.application.routes.url_helpers

Opens a bundled gem in the editor

export BUNDLER_EDITOR=subl && bundle open cancan

Check production state

if Rails.env.production?

Respond to formats

respond_to do |format|
  format.html
  format.json { render json: @apps.to_json }
end

Generate views with Bootstrap

# rails generate bootstrap:themed CONTROLLER_PATH [MODEL_NAME]
rails g bootstrap:themed admin/items item

UTF-8 for seeds.rb

# Just add the following line as the first line of your seeds.rb
# -*- coding: utf-8 -*-

Rollback multiple migrations

rake db:rollback STEP=2

Generate referenced model

rails generate model Comment body:text post:references

Truncates all *.log files in log/ to zero bytes

rake log:clear

Run rails in production using webrick

rails s --environment=production

Migrate production database

rake db:migrate RAILS_ENV="production"

Clone development db to test db

rake db:test:clone

Setup deployment to a VPS

cap deploy:setup

Local precompile assets

rake assets:precompile RAILS_ENV=development

Source location

>> Project.instance_method(:trash).source_location
=> ["/Users/qrush/37s/apps/bcx/app/models/project.rb", 90]

>> app.method(:get).source_location
=> ["/Users/qrush/.rbenv/versions/1.9.3-p194/lib/ruby/gems/1.9.1/bundler/gems/rails-7d95b814583b/actionpack/lib/action_dispatch/testing/integration.rb", 32]

Helper in a console

>> helper.link_to "Home", app.root_path
=> "<a href=\"/\">Home</a>"

Random Rspec stuffs

# https://github.com/oozou/addresstalk/pull/300#discussion_r3389770
# have_selector works only on :href

# https://github.com/oozou/addresstalk/pull/326#discussion_r3932704
have_field field, :with => title

expect(html).to have_selector 'div#share-community div.modal-header',
  :text => community.name

Clear all resque workers

Resque.workers.each {|w| w.unregister_worker}

Delete all ElasticSearch index

curl -XDELETE 'http://localhost:9200/'

Basic ElasticSearch services

http://localhost:9200/_mapping?pretty=1  # get all mapping keys
http://localhost:9200/slimwiki_development/page/_search?pretty=1  # searching

Vim

Replace among opened buffers

:bufdo %s/pattern/replace/ge | update

Magic modes

/    # Magic, default, e.g. need to use \+
/\v  # Very magic, no need to use \+
/\M  # Nomagic, need to use \. and \*
/\V  # Very Nomagic, like Nomagic but also need to use \$
     # http://andrewradev.com/2011/05/08/vim-regexes/

Tabs to spcaes

:retab

OSX

OSX Screencast to animated GIF

ffmpeg -i in.mov -s 600x400 -pix_fmt rgb24 -r 10 -f gif - | gifsicle --optimize=3 --delay=3 > out.gif
# -r 10 tells ffmpeg to reduce the frame rate from 25 fps to 10
# -s 600x400 tells ffmpeg the max-width and max-height
# --delay=3 tells gifsicle to delay 30ms between each gif
# --optimize=3 requests that gifsicle use the slowest/most file-size optimization

screengif --max-width 600 --output out.gif -v -f 0 -d 2 -r 60 --delay-last 200 --input Untitled\ 20.mov

Open Characters

option + command + T

Copy the SSH key to your clipboard

pbcopy < ~/.ssh/id_rsa.pub

Go2Shell configurations

open -a Go2Shell --args config

[youtube-dl] list all available formats

youtube-dl -F [YOUTUBE_URL]

[youtube-dl] download selected format video

youtube-dl -f [NUMBER] [YOUTUBE_URL]

Using ImageMagick to make sharp web-sized photographs

ls *.jpg|while read i;do gm convert $i -resize "900x" -unsharp 2x0.5+0.5+0 -quality 98 `basename $i .jpg`_s.jpg;done

# Note: To use imagemagick rather than graphicsmagick, just remove the "gm"
# https://even.li/imagemagick-sharp-web-sized-photographs/

Find and delete

find *.png -delete

Find recursively and delete

find **/*.orig -exec rm {} \;

Generate ssh key

ssh-keygen -t rsa -C "[email protected]"

Add ssh key

ssh-add ~/.ssh/id_rsa

Delete all ssh keys

ssh-add -D

List saved ssh keys

ssh-add -l

Create a bootable USB of OSX Maverick

sudo /Applications/Install\ OS\ X\ Mavericks.app/Contents/Resources/createinstallmedia --volume /Volumes/UNTITLED --applicationpath /Applications/Install\ OS\ X\ Mavericks.app

Fix image rotation

jhead -autorot *.JPG

Resize and crop images

sips --resampleWidth 1080 *.JPG && sips --cropToHeightWidth 720px 1080px *.JPG

Node.js

Specifying a version of Node.js or npm

{
  "name": "myapp",
  "version": "0.0.1",
  "engines": {
    "node": "0.8.x",
    "npm":  "1.1.x"
  }
}

// https://devcenter.heroku.com/articles/nodejs-versions

Setting NODE_ENV on Heroku

heroku config:add NODE_ENV=production

PostgreSQL

Display information about current connection

\conninfo

List all tables

\d

Use/connect to a database

\c [DATABASE_NAME]
psql [DATABASE_NAME]

SQL Dump

pg_dump [DATABASE_NAME] > [OUTPUT_FILE_NAME]

Restoring the dump

psql [DATABASE_NAME] < [INPUT_FILE_NAME]

Describe table

\d [TABLE_NAME]

List all databases

\list
psql -l

Generate new uncompressed data-only backup (Heroku dump -> mysql)

pg_dump --data-only --column-inserts --format p -f [BACKUP_NAME.sql] [POSTGRES_DB_NAME]
# then use http://www.lightbox.ca/pg2mysql.php

Start PostgreSQL installed from homebrew

postgres -D /usr/local/var/postgres
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Import dumped psql in local machine

pg_restore -O -d [APP_DATABASE_NAME] [DUMPED_FILE_NAME]

Heroku

Migrate database

heroku run rake db:migrate

Restoring the dump

heroku pgbackups:restore SHARED_DATABASE '[RAW_GIST_FILE_URL]'

List all backups

heroku pgbackups

Create a publicly accessible URL for a backup

heroku pgbackups:url [BACKUP_ID]

Database information

heroku pg:info

Open addons console

heroku addons:open [ADDON_NAME]

Heroku PG local/prod restoration

curl -o tmp/latest.dump `heroku pgbackups:url --app addresstalk`
pg_restore --verbose --clean --no-acl --no-owner -h localhost -d addresstalk_development tmp/latest.dump
heroku pgbackups:restore DATABASE --app addresstalk-staging `heroku pgbackups:url --app addresstalk`

Sublime Text 2

Reopen closed tabs

Shift + Cmd + T

Using Package Control

Shift + Cmd + P > install
# Package Control: Install Package

Installing Package Control

# Control + `

import urllib2,os;pf='Package Control.sublime-package';ipp=sublime.installed_packages_path();os.makedirs(ipp) if not os.path.exists(ipp) else None;open(os.path.join(ipp,pf),'wb').write(urllib2.urlopen('http://sublime.wbond.net/'+pf.replace(' ','%20')).read())

# restart & browse to Preferences -> Package Settings

Add an additional cursor at all occurrences

Ctrl + Command + G

Git

Rebase with interactive

git rebase -i HEAD^
git rebase -i HEAD~5

Deleting remote branch

git push origin :newfeature

Remove both untracked and ignored files

git ls-files --other | xargs rm -f

Removing ignored files

git ls-files --ignored --exclude-standard --other | xargs rm -f

Remove untracked files

git ls-files --exclude-standard --other | xargs rm -f

Push to a different branch

git push heroku expressjs:master

Ubuntu

Install firewall

sudo apt-get install ufw

Restart Nginx

sudo service nginx restart

Restart php-fpm

sudo service php5-fpm restart

Vim Nginx default configuration

sudo vim /etc/nginx/sites-available/default

Place the public key on the virtual server

cat .ssh/id_rsa.pub | ssh [email protected] "cat >> ~/.ssh/authorized_keys"

Restart machine

sudo shutdown -r now

Restart PostgreSQL

/etc/init.d/postgresql restart

Redis

Delete keys matching a pattern

redis-cli KEYS "prefix:*" | xargs redis-cli DEL

Laravel

Generate the Application Key

php artisan key:generate

Generate a migration

php artisan migrate:make [MIGRATION_NAME_WITH_UNDERSCORE]

Migrate database

php artisan migrate:install
php artisan migrate
php artisan migrate:rollback