NodeJs について

April 22 [Fri], 2011, 13:45
すっかり春になりましたね。お久しぶりです、中村です。

最近全然更新していなかったので、久しぶりにコネタを。

去年からJavaScript関連で何かと話題にあるNodeJSについて簡単なメモ書きをしておきます。
設定環境はWindowsなので、Cygwinでいきます。
Cygwinに設定は、省きます。

で、インストールされたとして以下の手順で進めます。

0.前提として
gcc-c++、make、openssl-devel
が入っていること!

1)ここからダウンロードします。
ダウンロードしたら、お好きな場所に展開します。

2)インストールする。
 > ./configure --prefix=/usr/local/node
 >make
 >sudo make install

以上で完了です。$NODE_JS_HOME$のbin以下にパスを通しておけば、終わりです。試しに以下のようにバージョンを確認してみましょう。

>node -v

次にNPMもインストールしちゃいましょう。
NPMとはnode.jsのパッケージ管理ソフトです。RubyだとRVMがありますね。それのnode.js版です。

これは、インストールには「crul」を使いますので、注意してください。

インストールされていれば、次の1行ですみます。

>curl http://npmjs.org/install.sh | sh

以上で終わりです。

ちなみにここ3ヶ月はRails3のサンプル本の執筆をしていました。出版はまだ先ですが、良いものを世の中に出したいと思います。

Rails探求の旅(Herokuをいじった)

December 20 [Mon], 2010, 14:32
先日Rails勉強会でHerokuについて触れましたので、復習の意味も込めて簡単にまとめす。

1)Herokuとは
Rubyで作られているクラウド環境。RubyOnRailsのアプリを開発できる。Herokuはここから。

2)やり方
ざっくりというと、まずHEROKU用にプラグインを入れる。で、Git経由でアプリをダウンロードするので、Gitの設定もしておく
>gem install heroku
>heroku create hogehoge

3)特徴
・プラグインも結構あるので、色々使える。例外起きたらメールとか、Solr使えたり
・Memcached、Vanish、Dyno Gridを使っている。けど、最大24スレッド(だったはず)


4)使いどころ
・試して何か動かすにはいい。勉強会用の環境なんか良いかも


以上、ざっとこんな感じです。
試してみると、色々面白いかも。
ちなみに、事例としては、以下のサイトがあります。


Notwife
Lokka



Rails探求の旅(Rails3で複数DB接続)

December 16 [Thu], 2010, 20:05
Rails3で複数のDBに接続を切り替えたい場合は以下の手順でできます。
1)例えばUserクラスがあるとすると以下のコードを追加します。

class User < ActiveRecord::Base
def self.master_connection(conf)
User.establish_connection Rails.configuration.database_configuration[conf]
end
end

2)次にControllerの中で適宜接続先を切り替えます。例えば以下のように!

def index
User.master_connection "development"
@users = User.all
User.master_connection "test"
@users2 = User.all

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @users }
end
end

上記のように記述すると/config/database.ymlの接続情報をプログラムの中で切り替えて使うことができます。

これが出来て何が嬉しいか・・・。Master/Slaveのように用途によって接続先を切り替えてアプリケーションの負荷対応ができます。

Rails探求の旅(Rails3とMongodb)

December 08 [Wed], 2010, 14:35
最近NoSQLに興味があり、Rails3とMongoDBの連携を調べました。今回はその作業ログです。

○MongoDbのインストール
wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.6.4.tgz
> tar zxfv mongodb-linux-i686-1.6.4.tgz
> cd mongodb-linux-i686-1.6.4/bin
> mkdir -p /tmp/mongodb

○MongoDBの起動
>cd mongodb-linux-i686-1.6.4/bin
> ./mongod --dbpath /tmp/mongodb

○Rails3アプリ対応(参考
・Gemfileに以下を追加

 gem "mongoid", "2.0.0.beta.17"
 gem "bson_ext", "1.1.1"


・「bundle install」を実行

・モデル生成
>rails g model Dream title:string descritpion:string category:string
>rails generate mongoid:config

・Configファイルを設定
設定ファイルを生成しMongoDBを使うようにする
./confing/mongoid.yml

/******************************************
defaults: &defaults
host: 192.168.198.236
port: 27017
slaves:
- host: slave1.local port: 27018
- host: slave2.local
port: 27019
autocreate_indexes: false
allow_dynamic_fields: true
include_root_in_json: false
parameterize_keys: true
persist_in_safe_mode: false
raise_not_found_error: true
reconnect_time: 3

development:
<<: *defaults
database: drecom_development

test:
<<: *defaults
database: drecom_test

# set these environment variables on your prod server
production:
<<: *defaults
host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
~
************************************************/

・config/application.rbの先頭を以下のように編集する

#require 'rails/all'
require 'action_controller/railtie'
require 'action_mailer/railtie'
require 'active_resource/railtie'


・モデルのクラスの設定
class Hoge
include Mongoid::Document
field :title, :type => String
field :descritpion, :type => String
field :category, :type => String
attr_protected :_id
end

以上のように設定していれば、問題ないはずです。
モレがあったら、追記します

○サンプル作成
参考:http://ursm.jp/mongo

MongoDBの設定
http://gihyo.jp/dev/serial/01/ruby/0031

Rails探究の旅(Windowsでのローカル環境構築)

November 14 [Sun], 2010, 22:15
健康診断の日が間近に迫り、不安になるナカムラです。
今日は、Rails3のローカル環境(Windowns版 )の構築手順についてです。

1)Ruby1.9.2 インストール
ここからダウンロードしてインストールします

2)SQLite3 インストール
ここからダウンロードしてsqlite3.dll を C:\Ruby192\bin(上の1)でインストールした先) へコピーします。

3)Rails3 インストール
GEMのインストールでRails3がインストールされます。
>$ gem install rails

以上で準備は完了です。

Rails探求の旅(Rails3環境構築)

November 11 [Thu], 2010, 14:17
最近レンタルサーバを諸事情により解約した中村です。
レンタルサーバを解約したので、今新しくサーバ環境を会社の個人環境に作っています。

今回はその設定について、備忘録的に書きます。

○nginxのインストール(http://wiki.nginx.org/Install)
1)必須ファイルを取得
yum install -y httpd-devel pcre perl pcre-devel zlib zlib-devel GeoIP GeoIP-devel

2)wgetで取得
wet http://sysoev.ru/nginx/nginx-0.8.53.tar.gz

3)ビルドとインストール
>./configure
>make
>sudo make install

○使い方
・起動
sudo /usr/local/nginx/sbin/nginx

・停止
sudo kill `cat /usr/local/nginx/logs/nginx.pid`

○Unicornの設定
1)インストール
gem install unicorn

2)設定ファイルを${RAILS_APP_ROOT}/configいかに作成
例も載せます。
--------------ここから---------------------
# Sample verbose configuration file for Unicorn (not Rack)
#
# This configuration file documents many features of Unicorn
# that may not be needed for some applications. See
# http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb
# for a much simpler configuration file.
#
# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete
# documentation.

# Use at least one worker per core if you're on a dedicated server,
# more will usually help for _short_ waits on databases/caches.
worker_processes 4

# Help ensure your application will always spawn in the symlinked
# "current" directory that Capistrano sets up.
working_directory "${RAILS_APP_ROOT}" # available in 0.94.0+

# listen on both a Unix domain socket and a TCP port,
# we use a shorter backlog for quicker failover when busy
listen "/tmp/unicorn.sock", :backlog => 64
#listen 8081, :tcp_nopush => true

# nuke workers after 30 seconds instead of 60 seconds (the default)
timeout 30

# feel free to point this anywhere accessible on the filesystem
pid "${RAILS_APP_ROOT}/log/unicorn.pid"

# By default, the Unicorn logger will write to stderr.
# Additionally, ome applications/frameworks log to stderr or stdout,
# so prevent them from going to /dev/null when daemonized here:
stderr_path "${RAILS_APP_ROOT}/log/unicorn.stderr.log"
stdout_path "${RAILS_APP_ROOT}/log/unicorn.stdout.log"

# combine REE with "preload_app true" for memory savings
# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
GC.copy_on_write_friendly = true

before_fork do |server, worker|
# the following is highly recomended for Rails + "preload_app true"
# as there's no need for the master process to hold a connection
defined?(ActiveRecord::Base) and
ActiveRecord::Base.connection.disconnect!

# The following is only recommended for memory/DB-constrained
# installations. It is not needed if your system can house
# twice as many worker_processes as you have configured.
#
# # This allows a new master process to incrementally
# # phase out the old master process with SIGTTOU to avoid a
# # thundering herd (especially in the "preload_app false" case)
# # when doing a transparent upgrade. The last worker spawned
# # will then kill off the old master process with a SIGQUIT.
# old_pid = "#{server.config[:pid]}.oldbin"
# if old_pid != server.pid
# begin
# sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
# Process.kill(sig, File.read(old_pid).to_i)
# rescue Errno::ENOENT, Errno::ESRCH
# end
# end
#
# Throttle the master from forking too quickly by sleeping. Due
# to the implementation of standard Unix signal handlers, this
# helps (but does not completely) prevent identical, repeated signals
# from being lost when the receiving process is busy.
# sleep 1
end

after_fork do |server, worker|
# per-process listener ports for debugging/admin/migrations
# addr = "127.0.0.1:#{9293 + worker.nr}"
# server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true)

# the following is *required* for Rails + "preload_app true",
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection

# if preload_app is true, then you may also want to check and
# restart any other shared sockets/descriptors such as Memcached,
# and Redis. TokyoCabinet file handles are safe to reuse
# between any number of forked children (assuming your kernel
# correctly implements pread()/pwrite() system calls)
end
------------------------------------------

3)操作
・起動
unicorn_rails -c config/unicorn-config.rb -E production -D

・停止
sudo pgrep -f 'unicorn_rails master'
sudo kill -QUIT ×××


○nginxの設定ファイルの編集
------------------------------------------
#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;


events {
worker_connections 1024;
}


http {
include mime.types;
default_type application/octet-stream;

#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';

#access_log logs/access.log main;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#gzip on;
upstream unicorn {
server unix:/tmp/unicorn.sock;
}
server {
listen 80;
#server_name localhost;
server_name 127.0.0.1;

#charset koi8-r;

access_log ${RailsAPP_ROOT}/log/pinejuice.jp.access.log;
root ${RailsAPP_ROOT}/public;
error_log ${RailsAPP_ROOT}/log/error.log;
location / {
if (!-f $request_filename) {
# proxy_set_header X-Real-IP $remote_addr;
# proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# proxy_set_header Host $http_host;
proxy_pass http://unicorn;
}

}
#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/rails/lifepack_task_board/public;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}


# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;

# location / {
# root html;
# index index.html index.htm;
# }
#}


# HTTPS server
#
#server {
# listen 443;
# server_name localhost;

# ssl on;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;

# ssl_session_timeout 5m;

# ssl_protocols SSLv2 SSLv3 TLSv1;
# ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
# ssl_prefer_server_ciphers on;

# location / {
# root html;
# index index.html index.htm;
# }
#}

}
----------------------------------------

こんな感じで設定したら、いけました。
以下のサイトが参考になります。

参考1
参考2
参考3


Rails探求の旅(Rails3)

November 09 [Tue], 2010, 20:01
忘れないように、Rails3で使うRakeコマンドの一覧を載せます

■rakeタスク 一覧
rake -T

■rake db:abort_if_pending_migrations

実行されてないmigrationを教えてくれる。

■rake db:charset

データベースの文字コードを教えてくれる。

■rake db:collation

データベースの照合順序を教えてくれる。

■rake db:create

database.ymlの内容でデータベースを作る。

−「RAILS_ENV」オプション

productionのが作りたければrake db:create RAILS_ENV=production

■rake db:create:all

database.ymlに定義してあるデータベースを全部作る。

■rake db:drop

createの逆。

■rake db:drop:all

create:allの逆。

■rake db:migrate:redo

migrationを指定STEP数だけやりなおす。

STEPの指定はSTEP=nで。

■rake db:migrate:reset

drop、create、migrate全てやる。

■rake db:reset

drop、create、schema.rbから復帰させる。

■rake db:rollback

migrationのバージョンをSTEP=nで戻す。

■rake db:version

Rails探究の旅(Rails3の国際化対応について)

November 03 [Wed], 2010, 10:35
どうも、10月はプライベートが忙しかったですが、11月になり落ち着いてきました中村です。
すっかり秋ですね。今年は暑かったので、今の気候がなんだか気持ちがイイです。

さて久しぶりですが、Rails3について書きます。今日のテーマは「国際化対応」です。

先日自信の勉強のためにWebタスク管理ツールを公開しましたが、実はこれは日本語対応がされてませんでした。
というのは、エラーメッセージがモロに英語です。

で、この英語表記を日本語に直したくて、色々調べました。

結論から言うと以下のファイルを修正及び追加擦る必要があります。

 ./config/locals/ja.yml ・・・・・・追加
./config/application.rb ・・・・・・修正

そもそもRails3で国際化対応を担当しているプラグインが「I18n」です。参考

で、このプラグインを作った方はドイツ人(?)だったらしく、デフォルトが英語しかありません。で、日本語に対応するにはそれに対応するYMLファイルを取ってきて、./config/locals以下に配置しないとダメなようです。
で、何か良いサンプルがないかと思ったところこちらから各国のYMLファイルが手に入りました。ので、ja.ymlを取ってきて配置しましょう。

続いて今デフォルトが英語なので、それを日本語に変えましょう。
./config/application.rb の中の
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :ja # <=======

上記「config.i18n.default_locale =」のところをコメントアウトを外し、deになっているところをjaに変更しましょう。

以上で、エラーメッセージも日本語表記になります。

全文検索エンジン

September 08 [Wed], 2010, 19:34
最近技術者ブログへの記載が滞っている中村です。
今回は全文検索エンジンFessについてです。FessはSolrをラップしたアプリケーションです。

これをいじっていようと思ったのは、どなたかのブログか何かに「5分で構築できる検索エンジン」というのを目にしたからです。では、サクっとインストールしていじってみましょう。


1)環境設定
まずは<リンク: http://fess.sourceforge.jp/ja/index.html>ここからFessをダウンロードします。Fessをダウンロードしたら適当なところに解凍します。続いて「Java6」をインストールします。
これで準備完了です。後は、Fessをインストールした場所に行き、binフォルダ直下の「./catalina..sh start」をたたいて起動すれば完了です。

2)動きの確認
ローカルならば「http://localhost:8080/fess/admin」にアクセスすると管理ツールがみれます。
管理ツールでは、検索対象のWEBページのクロール設定、検索対象のデータが入っているDBのクロース設定、ファイルシステムから検索データをクロースする設定などがあります。
一番簡単なのは、WEBページのクロールなので,試しにやる場合はログイン後に「ウェブ」という欄をクリックし、新規クロール先の設定を追加してください。
※ログインは「admin/admin」で入れます。



3)カスタマイズ
以下の機能が用意されているので、今後使ってみたいと思っています
・レプリケーション機能
 Index更新用とSelect用とで分けて、負荷分散を行う。
・DBクロール
 こちらは簡単にできました。あとは検索結果項目をサイトに合わせて変更したいので、そちらもみていきたいと思います

以上です。

Rails探究の旅(Rails3とRails2の同居)

August 21 [Sat], 2010, 13:19
Rails3の勉強をここ最近急ピッチで進めている中村です。
ナレッジをドンドン蓄積していこうと思っています。

今回は、Rails3の勉強をすすめるにあたりに、複数のバージョンのRailsを一つのマシンにセットして、適宜切り替えて使えるようにする方法を紹介します。今回使う技術は「RVM」です。


1.設定方法
RVMを以下のサイトから取得し、インストールします。
>wget -O rvm-install http://rvm.beginrescueend.com/releases/rvm-install-latest
>sh rvm-install
>source .rvm/scripts/rvm

・設定ファイルのパスを登録します。
>echo 'if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then "' >> ~/.bashrc
>echo ' source "$HOME/.rvm/scripts/rvm" ; ' >> ~/.bashrc
>echo 'fi' >> ~/.bashrc

・Ruby1.9.2をインストールしてみましょう。
>rvm 1.9.2

・Ruby1.9.2を使うように切り替えてみましょう
>rvm use 1.9.2

・Rails3用のGEM設定を登録します。
>rvm gemset create 'rails3'

・次にRailsをセットアップします
>gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n
>gem install rails --pre

これでRails3の環境を作ることができました。
非常に簡単ですので、皆さんも試してみてください。


プロフィール
  • ニックネーム:GMOメディア開発部の面々
  • 性別:男性
  • 職業:専門職
読者になる
Java、PHP、Ruby、Scala、iPhoneアプリ、Androidアプリなどを開発しています。何かご質問があれば、どうぞ!
2011年04月
« 前の月  |  次の月 »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
最新トラックバック
最新コメント
更新お知らせ
このブログが更新されたら、メールでお知らせします!
更新メールを受取る