find_or_create_by・・・が素敵すぎる!
今さら知ったのかよ感がありますが、こんな便利メソッドがあったんですね。
知らなかった!
こいつを使うと
user = User.find_by_name("zakihaya") || User.new(name: "zakihaya")
が
user = User.find_or_create_by_name("zakihaya")
になる!
Rails4からは下のようなものが推奨になるみたいです。
user = User.find_or_create_by(name: "zakihaya")
Object#tryでインデクサを対象にする
まずはObject#tryについて
def try(method, *args, &block) ・・・ end
なんと!ブロックも使えるのか、知らなかった。
tryを使うと
@object ? @object.name : nil
が
@object.try(:name)
こんな感じで書けるようになります。
モデルのインスタンスを扱う時とかに非常に役立ちます。
で、このオブジェクトがインデクサメソッドを持ってるとして、
@object ? @object["key"] : nil
をtryを使って書くには
@object.try(:"[]", "key")
としてやればOK
Railsアプリを作る時の基本設定
自分用にメモ
Gemfile
source 'https://rubygems.org' gem 'rails', '3.2.6' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' gem 'sqlite3' gem 'mysql2' gem 'haml-rails' # Gems used only for assets and not required # in production environments by default. group :assets do gem 'sass-rails', '~> 3.2.3' gem 'coffee-rails', '~> 3.2.1' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer' gem 'uglifier', '>= 1.0.3' gem "twitter-bootstrap-rails" end gem 'jquery-rails' group :development, :test do gem 'rspec' gem 'rspec-rails' gem 'spork' gem 'guard-spork' gem 'growl' gem 'guard-rspec' gem 'fabrication' gem 'capybara' gem 'capybara-webkit' gem 'email_spec' gem 'faker' gem 'sunspot-rails-tester' gem 'cucumber-rails', :require => false gem 'guard-cucumber' gem 'awesome_print' gem 'pry-nav' end # To use ActiveModel has_secure_password # gem 'bcrypt-ruby', '~> 3.0.0' # To use Jbuilder templates for JSON # gem 'jbuilder' # Use unicorn as the web server # gem 'unicorn' # Deploy with Capistrano # gem 'capistrano' # To use debugger # gem 'ruby-debug19', :require => 'ruby-debug'
application.rb
module RailsApp class Application < Rails::Application ・ ・ ・ config.time_zone = 'Tokyo' config.active_record.default_timezone = :local config.i18n.default_locale = 'ja' config.generators do |g| g.template_engine :haml g.test_framework :rspec end ・ ・ ・ end end
rails g rspec:install rails g bootstrap:install rails g bootstrap:layout application
rails s を実行すると uninitialized constant Syck::MergeKey (NameError) というエラーが発生する
localhost $ bundle exec rails s localhost $ RAILS_ROOT/vendor/bundle/ruby/1.9.1/gems/configatron-2.8.0/lib/configatron/store.rb:324:in `<class:Store>': uninitialized constant Syck::MergeKey (NameError)
こんなエラーが出るのでなんだろうなーと思って30分くらいハマっていたが、何の事はない、Rubyのバージョンを1.9.3→1.9.2にしたら動いた・・・。
エラーわかりづらすぎ。
fluentdを使ってnginxのログを溜めてみるメモ
まずはローカルのファイルにログをためてみる
fluentdインストール
td-agentというパッケージを使う。
[root@localhost ~]# cat /etc/yum.repos.d/td.repo
[treasuredata]
name=TreasureData
baseurl=http://packages.treasure-data.com/redhat/$basearch
gpgcheck=0
[root@localhost ~]# yum install td-agent
ログを置くフォルダの準備
nginxのログフォーマット変更
log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time';
…(省略)
access_log /var/log/nginx/hayazaki.access.log custom;
nginx再起動
/etc/td-agent/td-agent.conf(fluentd設定ファイル)
type file
path /var/log/archive/nginx.access.hayazaki
time_slice_format %Y%m%d_%H%M
time_slice_wait 30s
time_format %Y-%m-%d %H:%M:%S
fluentd起動
mongodbにためてみる
mongodbインストール
[root@localhost ~]# cat /etc/yum.repos.d/10gen.repo
[10gen]
name=10gen Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64
gpgcheck=0
[root@localhost ~]# yum install mongo-10gen-server
[root@localhost ~]# service mongod start
この時点では当然まだmongoは空
MongoDB shell version: 2.0.2
connecting to: test
> show dbs;
local (empty)
fluent-plugin-mongoのインストール
/etc/td-agent/td-agent.conf
ファイルに出力していた部分をmongoに出力するように書き換え
type mongo
host localhost
database fluent
collection nginx
td-agent再起動
下のメッセージが出る
**Notice: C extension not loaded. This is required for optimum MongoDB Ruby driver performance.
You can install the extension as follows:
gem install bson_ext
If you continue to receive this message after installing, make sure that the
bson_ext gem is in your load path and that the bson_ext and mongo gems are of the same version.
bson_extをインストール後、td-agent再起動
[root@localhost ~]# /etc/init.d/td-agent restart
mongodbに出力されているか確認
[root@localhost ~]# mongo
MongoDB shell version: 2.0.6
connecting to: test
> use fluent
switched to db fluent
> db.nginx.find();
{ "_id" : ObjectId("4fdce3b95ef6b1741f000001"), "host" : "127.0.0.1", "user" : "-", "method" : "GET", "path" : "/", "code" : "200", "size" : "151", "referer" : "-", "agent" : "curl/7.19.7 (x86_64-unknown-linux-gnu) libcurl/7.19.7 NSS/3.12.7.0 zlib/1.2.3 libidn/1.18 libssh2/1.2.2", "response_time" : "\"0.000\"", "time" : ISODate("2012-06-16T19:50:24Z") }
こんな感じでクエリを投げれば404のログだけ抽出できる
ホットコーナーを利用してお手軽に画面をロックする
WindowsでいうWindowsキー+lショートカットみたいなのがMacにも無いのかなーと思っていたら、ちょっと違うけど方法を発見しました。
OSは10.7 Lionです。
- システム環境設定で「デスクトップとスクリーンセーバ」を選ぶ
- スクリーンセーバーのほうを選んで、左下の「ホットコーナー」をクリック
- 四隅のどこかに「スクリーンセーバを開始する」を設定
- 設定したところにカーソルを持って行くとヤッホーイとなります
スクリーンセーバー起動時にパスワードを聞くようにするには
- システム環境設定でセキュリティとプライバシー
- 一般→スリープとスクリーンセーバでパスワードを要求にチェック
です。
ちなみに、Locktightというのを入れてもいけるようです。