Gruntの基本をおさえておく
仕事でGrunt使う機会があったので、きちんと基本を押さえておくことにしました。
Gruntってなに?
WEBフロント開発で使うJavaScriptとCSSの変換ツール
目的は、JSやCSSを書きやすい形で実装して、ブラウザで実行できる形に変換する環境を提供すること。
主にやることは下記。
- CoffeScript/TypeScriptのJS変換
- SCSS/LESSのCSS変換
- JavaScript/CSSの圧縮(minify)
環境構築
例えばこんな感じで。nodejsが必要なのでnvmでインストール、gruntコマンドを使うためにgrunt-cliをインストールしています。
cd ~ curl -o- https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash export NVM_DIR="/home/vagrant/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" nvm install 6.9.1 nvm alias default 6.9.1 npm update -g npm npm install -g grunt-cli
プロジェクトつくる
my-projectというディレクトリにpackage.jsonを作成します。
package.jsonはこのプロジェクトで使用したいプラグインを記述するファイルです。
mkdir my-project cd my-project/ npm init
Gruntをインストール
npm install grunt -save-dev npm install grunt-contrib -save-dev npm install grunt-contrib-concat -save-dev npm install grunt-contrib-cssmin -save-dev npm install grunt-contrib-uglify -save-dev npm install grunt-contrib-watch -save-dev npm install grunt-contrib-connect -save-dev
Gruntがインストールされます。-save-devオプションでpackage.jsonにも追記されます。
ついでにpluginもインストールしています。
※warning出まくるけど無視(していいのかわからんけど)。
Gruntfile.jsの作成
Grunt実行時の処理を記述するGruntfile.jsを作成します。
たとえばこんな感じ。
module.exports = function(grunt) { //Gruntの設定 grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // ファイル結合だけ concat: { js: { src: ['src/js/*.js'], dest: 'build/application.js' }, css: { src: ['src/css/*.css'], dest: 'build/application.css' } }, // CSSの結合+圧縮 cssmin: { minify: { src: ['src/css/*.css'], dest: 'build/application.min.css' } }, // JSの結合+圧縮 uglify: { build: { src: ['src/js/*.js'], dest: 'build/application.min.js' } }, // ファイル変更を感知して自動的にタスク実行する設定 // いちいちgruntコマンド叩かなくてよくなる watch: { css: { files: ['src/css/*.css'], tasks: ['concat:css', 'cssmin'] }, js: { files: ['src/js/*.js'], tasks: ['concat:js', 'uglify'] } }, // 簡易サーバ // grunt connect で起動する connect: { local: { options: { port: 9998, livereload: true, keepalive: true, } } }, }); // プラグインを読み込む // usage: http://gruntjs.com/plugins grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-connect'); // grunt 実行されるタスク grunt.registerTask('default', ['concat', 'cssmin', 'uglify']); // grunt dev で実行されるタスク grunt.registerTask('dev', ['concat', 'cssmin', 'uglify', 'watch']); };
WordPressのサイトURLを変更する一撃SQL
WordPressのDBにはサイトURLの情報があちこちに散りばめられて登録されています。
なので、ローカルで作ったサイトを本番に反映するとき、サイトのドメインを変えるときなど、サイトのURLを変えて動作させたいときはやっかいです。DBの中のURL情報をまとめて書き換える必要があります。
ここに記すは、WordPressのURL情報を書き換える一撃SQLです。
※@before, @after の内容は適宜読み替えてください。
-- 変数の定義 SET @before="before.jp"; SET @after="after.jp"; SET @scheme="http://"; -- wp_options siteurl行のoption_valueを更新 UPDATE wp_options SET option_value = CONCAT(@scheme, @after) WHERE option_name = 'siteurl'; -- wp_options home行のoption_valueを更新 UPDATE wp_options SET option_value = CONCAT(@scheme, @after) WHERE option_name = 'home'; -- 記事に書かれている画像タグの書き換え UPDATE wp_posts SET post_content = REPLACE(post_content, @before, @after); -- メディアに登録されるURLの書き換え UPDATE wp_posts SET guid = REPLACE(guid, @bofore, @after);
Vagrant+シェルでRails開発サーバを作る
新規案件でRails開発サーバを準備する必要があり、Vagrantとシェルのプロビジョニングで作成したときのメモです。
プロビジョニングにシェルを使用したのは、開発用PCがWindowsのためです。
無理してchefとか使おうとすると、環境構築を楽にするための環境構築が大変になるというよくわからないことになりそうでしたので。
下記ページを大いにパクらせて参考にさせていただきました。多謝です!
Rails開発のための仮想環境をvagrantでつくる - Qiita
主にインストールされるもの
- CentOS 6.7
- MySQL 5.6
- sqlite
- memcached
- rbenv
- ruby 2.3.1
- Git
- vim
- Nokogiriに必要なライブラリ
- ImageMagickに必要なライブラリ
※CentOS7/MySQL5.7の罠は回避。
よし作ろう
前提:VirtualBoxとVagrantはインストール済
1.boxファイルを取得
vagrant box add CentOS_6_7 https://github.com/CommanderK5/packer-centos-template/releases/download/0.6.7/vagrant-centos-6.7.box
2.初期設定
cd ~ mkdir centos6-rails cd centos6-rails vagrant init CentOS_6_7
3.Vagrantfileを作成
下記のように書き換える
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| GUEST_RUBY_VERSION = '2.3.1' # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. config.ssh.username = "vagrant" config.ssh.password = "vagrant" # Every Vagrant development environment requires a box. You can search for # boxes at https://atlas.hashicorp.com/search. config.vm.box = "CentOS_6_7" config.vm.hostname = "centos6-rails" # Disable automatic box update checking. If you disable this, then # boxes will only be checked for updates when the user runs # `vagrant box outdated`. This is not recommended. # config.vm.box_check_update = false # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine. In the example below, # accessing "localhost:8080" will access port 80 on the guest machine. # config.vm.network "forwarded_port", guest: 3000, host: 3000 # Create a private network, which allows host-only access to the machine # using a specific IP. config.vm.network "private_network", ip: "192.168.33.10" # Create a public network, which generally matched to bridged network. # Bridged networks make the machine appear as another physical device on # your network. # config.vm.network "public_network" config.vm.network "public_network", ip: "192.168.135.227" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. # config.vm.synced_folder "../data", "/vagrant_data" # Provider-specific configuration so you can fine-tune various # backing providers for Vagrant. These expose provider-specific options. # Example for VirtualBox: # config.vm.provider "virtualbox" do |vb| # Display the VirtualBox GUI when booting the machine vb.gui = false # Customize the amount of memory on the VM: vb.memory = "4096" end # # View the documentation for the provider you are using for more # information on available options. # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies # such as FTP and Heroku are also available. See the documentation at # https://docs.vagrantup.com/v2/push/atlas.html for more information. # config.push.define "atlas" do |push| # push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME" # end # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about their specific syntax and use. # config.vm.provision "shell", inline: <<-SHELL # apt-get update # apt-get install -y apache2 # SHELL FUNCTION_INSTALL =<<EOS function install { echo installing $1 shift yum -y install "$@" >/dev/null 2>&1 } EOS # development tools etc... config.vm.provision "shell", privileged: true, inline: <<-SHELL #{FUNCTION_INSTALL} yum -y update >/dev/null 2>&1 install "development tools" gcc-c++ glibc-headers openssl-devel readline libyaml-devel readline-devel zlib zlib-devel install "Git" git install "sqlite" sqlite sqlite-devel install "Nokogiri dependencies" libxml2 libxslt libxml2-devel libxslt-devel install "ImageMagick" ImageMagick ImageMagick-devel install "vim" vim-common vim-enhanced cp /etc/localtime /etc/localtime.org ln -sf /usr/share/zoneinfo/Asia/Tokyo /etc/localtime echo "ZONE=\"Asia/Tokyo\"" > /etc/sysconfig/clock service crond restart SHELL # MySQL5.6 config.vm.provision "shell", privileged: true, inline: <<-SHELL #{FUNCTION_INSTALL} yum install -y http://dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm >/dev/null 2>&1 install "MySQL" mysql mysql-server mysql-devel chkconfig --add mysqld chkconfig --level 345 mysqld on echo "Start and Initialize MySQL" service mysqld start >/dev/null 2>&1 mysql -uroot <<SQL -- SET ROOT PASSWORD -- UPDATE mysql.user SET Password=PASSWORD('vagrant') WHERE User='root'; -- REMOVE ANONYMOUS USERS -- DELETE FROM mysql.user WHERE User=''; -- REMOVE REMOTE ROOT -- DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1'); -- REMOVE TEST DATABASE -- DROP DATABASE IF EXISTS test; DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'; -- RELOAD PRIVILEGE TABLES -- FLUSH PRIVILEGES; CREATE USER 'vagrant'@'localhost'; SET PASSWORD FOR 'vagrant'@'localhost' = PASSWORD('vagrant'); GRANT ALL PRIVILEGES ON *.* to 'vagrant'@'localhost'; SQL SHELL # memcached config.vm.provision "shell", privileged: true, inline: <<-SHELL #{FUNCTION_INSTALL} install "memcached" memcached memcached-devel chkconfig --add memcached chkconfig --level 345 memcached on echo "Start and Initialize memcached" service memcached start >/dev/null 2>&1 SHELL # rbenv config.vm.provision "shell", privileged: false, inline: <<-SHELL echo installing rbenv git clone https://github.com/sstephenson/rbenv.git ~/.rbenv git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile echo 'eval "$(rbenv init -)"' >> ~/.bash_profile source ~/.bash_profile echo 'gem: --no-ri --no-rdoc' >> ~/.gemrc echo installing ruby#{GUEST_RUBY_VERSION} rbenv install #{GUEST_RUBY_VERSION} rbenv global #{GUEST_RUBY_VERSION} echo installing Bundler gem install bundler -N >/dev/null 2>&1 echo installing ruby-gemset cd ~/.rbenv/plugins/ git clone https://github.com/jf/rbenv-gemset.git SHELL # ntp config.vm.provision "shell", privileged: true, inline: <<-SHELL #{FUNCTION_INSTALL} install "ntp" ntp chkconfig ntpd on echo "Start and Initialize ntp" service ntpd start >/dev/null 2>&1 SHELL end
Vagrentの基本的な使い方メモ
準備
1.仮想化支援機構の有効化
2.VirtualBoxのインストール
3.Vagrantのインストール
4.CentOSのVirtualBoxへの登録
# 例 vagrant box add CentOS_6_3 https://dl.dropbox.com/sh/9rldlpj3cmdtntc/chqwU6EYaZ/centos-63-32bit-puppet.box
※公開box: http://www.vagrantbox.es/
5.Vagrant初期設定
> mkdir -p ~/Vagrant/centos6 > cd ~/Vagrent/centos6 > vagrant init CentOS_6_3 > ls # Vagrantfileファイルが存在することを確認
テキストエディタでVagrantfileを編集する。
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Authentication failure. Retrying が出るときはパスワード指定 config.ssh.username = "vagrant" config.ssh.password = "vagrant" config.vm.box = "CentOS_6_3" #コメントアウトを外す config.vm.network "private_network", ip: "192.168.33.10" end
Vagrantコマンド
# CentOS起動 vagrant up # CentOS停止 vagrant halt # サーバ廃棄 vagrant destroy # boxファイルを作る vagrant package # ローカルのboxファイルを登録する vagrant box add MyOS package.box
その他メモ
boxファイルの保存場所
Mac /Users/<username>/.vagrant.d/boxes/ Windows C:\Users\<username>\.vagrant.d\boxes\
日本語ドキュメント
http://lab.raqda.com/vagrant/index.html
Windows上でVirtualBox+Vagrant+CentOSによる仮想環境構築
http://qiita.com/hiroyasu55/items/11a4c996b0c62450940f
MySQLにblobで格納されたデータをまとめてファイル出力する
旧システムから新システムへのデータ移行の現場での一コマ。
DBにblobで格納されてた画像データをまとめてファイル出力したかったので、
PHPスクリプトを書いてみた。
<?php // DB接続情報 $db_host = 'localhost'; $db_user = 'root'; $db_pass = 'hogehoge01'; $db_name = 'db_name'; // 対象テーブルリスト $tables = array( 'a_images', 'b_images', 'c_images', 'd_images', 'e_images', 'f_images', ); $db = mysql_connect($db_host, $db_user, $db_pass); if ($db == false) { echo "database connect error\n"; exit; } echo "database connect\n"; if (!mysql_select_db($db_name, $db)) { echo "database $db_name is not exist\n"; exit; } echo "selcted database $db_name\n"; foreach ($tables as $table) { $sql = "SELECT * FROM $table"; $result = mysql_query($sql); while ($row = mysql_fetch_array($result)) { // ファイル出力先ディレクトリ $dir_path = 'files' . '/' . $table . '/' . $row['id']; mkdir($dir_path, 0777, true); // ファイル名はfilename, // バイナリはdataカラムに格納されている前提 $file_path = $dir_path . '/' . $row['filename']; $fp = fopen($file_path, 'w'); fwrite($fp, $row['data']); fclose($fp); echo 'File output from ' . $table . '(id = ' . $row['id'] . ")\n"; } }
シェルでカレントディレクトリ配下のテキストファイルの中身を一斉置換
よく忘れるのでメモ。
# カレントディレクトリ以下 hoge を含むファイルを確認 grep -rn "hoge/" ./. # hoge を fuga に一斉置換 grep -rl "hoge" ./. | xargs sed -i -e "s/hoge/fuga/g" ${1} # コピペ用 FROM=hoge TO=fuga grep -rl "${FROM}" ./. | xargs gsed -i -e "s/${FROM}/${TO}/g" ${1} # 特定のディレクトリを除外 grep -rl --exclude-dir=.git "${FROM}" ./. | xargs gsed -i -e "s/${FROM}/${TO}/g" ${1}