zakihayaメモ

RubyとRailsのことが中心

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というパッケージを使う。

参考
Installing td-agent for Redhat and CentOS / Installing td-agent daemon / Knowledge Base - Treasure Data Platform Support

[root@localhost ~]# vim /etc/yum.repos.d/td.repo
[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

ログを置くフォルダの準備

[root@localhost ~]# mkdir /var/log/fluent
[root@localhost ~]# chown td-agent:td-agent /var/log/fluent

nginxのログフォーマット変更

[root@localhost ~]#
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再起動
[root@localhost ~]# /etc/init.d/nginx stop
[root@localhost ~]# /etc/init.d/nginx start

/etc/td-agent/td-agent.conf(fluentd設定ファイル)


type tail
format /^(?[^ ]*) [^ ]* (?[^ ]*) \[(?

fluentd起動

[root@localhost ~]# service td-agent start

mongodbにためてみる

mongodbインストール

[root@localhost ~]# vim /etc/yum.repos.d/10gen.repo
[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は空

[root@localhost ~]# mongo
MongoDB shell version: 2.0.2
connecting to: test
> show dbs;
local (empty)

fluent-plugin-mongoのインストール

[root@localhost ~]# /usr/lib64/fluent/ruby/bin/fluent-gem install fluent-plugin-mongo

/etc/td-agent/td-agent.conf

ファイルに出力していた部分をmongoに出力するように書き換え


type mongo
host localhost
database fluent
collection nginx


td-agent再起動
[root@localhost ~]# /etc/init.d/td-agent restart

下のメッセージが出る
Starting td-agent: Able to load bson_ext version 1.4.0, but >= 1.5.2 is required.

**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 ~]# /usr/lib64/fluent/ruby/bin/gem install bson_ext
[root@localhost ~]# /etc/init.d/td-agent restart

mongodbに出力されているか確認

[root@localhost ~]# curl http://localhost/
[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のログだけ抽出できる
> db.nginx.find({code: "404"});

ホットコーナーを利用してお手軽に画面をロックする

WindowsでいうWindowsキー+lショートカットみたいなのがMacにも無いのかなーと思っていたら、ちょっと違うけど方法を発見しました。

OSは10.7 Lionです。

  1. システム環境設定で「デスクトップとスクリーンセーバ」を選ぶ
  2. スクリーンセーバーのほうを選んで、左下の「ホットコーナー」をクリック
  3. 四隅のどこかに「スクリーンセーバを開始する」を設定
  4. 設定したところにカーソルを持って行くとヤッホーイとなります

スクリーンセーバー起動時にパスワードを聞くようにするには

  1. システム環境設定でセキュリティとプライバシー
  2. 一般→スリープとスクリーンセーバでパスワードを要求にチェック

です。

ちなみに、Locktightというのを入れてもいけるようです。