Как сделать не меняя старого кода http://kmb.homelinux.net/tags/unobtrusive
четверг, 20 мая 2010 г.
Ruby on Rails делаем красивые формы ( поле ввода даты)
Как сделать не меняя старого кода http://kmb.homelinux.net/tags/unobtrusive
четверг, 10 декабря 2009 г.
Setup Ruby Enterprise Edition, nginx and Passenger (aka mod_rails) on Ubuntu
By Antonio Cangiano. Filed under Quick Tips, Ruby, Ruby on Rails
The following is a very short guide on setting up Ruby Enterprise Edition (REE), nginx and Passenger, for serving Ruby on Rails applications on Ubuntu. It also includes a few quick and easy optimization tips.
We start with setting up REE (x64), using the .deb file provided by Phusion:
wget http://rubyforge.org/frs/download.php/66163/ruby-enterprise_1.8.7-2009.10_amd64.deb
sudo dpkg -i ruby-enterprise_1.8.7-2009.10_amd64.deb
ruby -v
In output you should see “ruby 1.8.7 (2009-06-12 patchlevel 174)…” or similar. If this is the case, good; while you are there, update RubyGems and the installed gems:
sudo gem update --system
sudo gem update
Next, you’ll need to install nginx, which is a really fast web server. The Phusion team has made it very easy to install, but if you simply follow most instructions found elsewhere, you’ll get the following error:
checking for system md library ... not found
checking for system md5 library ... not found
checking for OpenSSL md5 crypto library ... not found
./configure: error: the HTTP cache module requires md5 functions
from OpenSSL library. You can either disable the module by using
--without-http-cache option, or install the OpenSSL library in the
system,
or build the OpenSSL library statically from the source with nginx by
using
--with-http_ssl_module --with-openssl=options.
Instead, we are going to install libssl-dev first and then nginx and its Passenger module:
sudo aptitude install libssl-dev
sudo passenger-install-nginx-module
Follow the prompt and accept all the defaults (when prompted to chose between 1 and 2, pick 1).
Before I proceed with the configuration, I like to create an init script and have it boot at startup (the script itself is adapted from one provided by the excellent articles at slicehost.com):
sudo vim /etc/init.d/nginx
The content of which needs to be:
#! /bin/sh
### BEGIN INIT INFO
# Provides: nginx
# Required-Start: $all
# Required-Stop: $all
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts the nginx web server
# Description: starts nginx using start-stop-daemon
### END INIT INFO
PATH=/opt/nginx/sbin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/opt/nginx/sbin/nginx
NAME=nginx
DESC=nginx
test -x $DAEMON || exit 0
# Include nginx defaults if available
if [ -f /etc/default/nginx ] ; then
. /etc/default/nginx
fi
set -e
. /lib/lsb/init-functions
case "$1" in
start)
echo -n "Starting $DESC: "
start-stop-daemon --start --quiet --pidfile /opt/nginx/logs/$NAME.pid \
--exec $DAEMON -- $DAEMON_OPTS || true
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon --stop --quiet --pidfile /opt/nginx/logs/$NAME.pid \
--exec $DAEMON || true
echo "$NAME."
;;
restart|force-reload)
echo -n "Restarting $DESC: "
start-stop-daemon --stop --quiet --pidfile \
/opt/nginx/logs/$NAME.pid --exec $DAEMON || true
sleep 1
start-stop-daemon --start --quiet --pidfile \
/opt/nginx/logs/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS || true
echo "$NAME."
;;
reload)
echo -n "Reloading $DESC configuration: "
start-stop-daemon --stop --signal HUP --quiet --pidfile /opt/nginx/logs/$NAME.pid \
--exec $DAEMON || true
echo "$NAME."
;;
status)
status_of_proc -p /opt/nginx/logs/$NAME.pid "$DAEMON" nginx && exit 0 || exit $?
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart|reload|force-reload|status}" >&2
exit 1
;;
esac
exit 0
Change its permission and have it startup at boot:
sudo chmod +x /etc/init.d/nginx
sudo /usr/sbin/update-rc.d -f nginx defaults
From now on, you’ll be able to start, stop and restart nginx with it. Start the server as follows:
sudo /etc/init.d/nginx start
Heading over to your server IP with your browser, you should see “Welcome to nginx!”. If you do, great, we can move on with the configuration of nginx for your Rails app.
Edit nginx’ configuration file:
sudo vim /opt/nginx/conf/nginx.conf
Adding a server section within the http section, as follows:
server {
listen 80;
server_name example.com;
root /somewhere/my_rails_app/public;
passenger_enabled on;
rails_spawn_method smart;
}
The server name can also be a subdomain if you wish (e.g., blog.example.com). It’s important that you point the root to your Rails’ app public directory.
The rails_spawn_method directive is very efficient, allowing Passenger to consume less memory per process and speed up the spawning process, whenever your Rails application is not affected by its limitations (for a discussion about this you can read the proper section in the official guide).
If you have lots of RAM (e.g., more than 512 MB) on your server, you may want to consider increasing you maximum pool size, with the directive passenger_max_pool_size from its default size of 6. Conversely, if you want to limit the number of processes running at any time and consume less memory on a small VPS (e.g., 128 to 256MB), you can decrease that number down to 2 (or something in that range). (Always test a bunch of configurations to find one that works for you). You can read more about this directive, in the official guide.
While you are modifying nginx’ configuration, you may also want to increase the worker processes (e.g., to 4, on a typical VPS) and add a few more tweaks (such as enabling gzip compression):
# ...
http {
passenger_root /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.5;
passenger_ruby /usr/local/bin/ruby;
include mime.types;
default_type application/octet-stream;
access_log logs/access.log;
sendfile on;
keepalive_timeout 65;
tcp_nodelay on;
gzip on;
gzip_comp_level 2;
gzip_proxied any;
server {
#...
When you are happy with the changes, save the file, and restart nginx:
sudo /etc/init.d/nginx restart
If you wish to restart Passenger in the future, without having to restart the whole web server, you can simply run the following command:
touch /somewhere/my_rails_app/tmp/restart.txt
Passenger also provides a few handy monitoring tools. Check them out:
sudo passenger-status
sudo passenger-memory-stats
That’s it, you are ready to go! I hope that you find these few notes useful.
четверг, 3 декабря 2009 г.
Установка Nokogiri на OS X
sudo port install libxml2 libxslt
gem install nokogiri -- --with-xml2-include=/opt/local/include/libxml2 --with-xml2-lib=/opt/local/lib --with-xslt-dir=/opt/local
или если поставили libxml2 из source соответственно
gem install nokogiri -- --with-xml2-include=/usr/local/include/libxml2 --with-xml2-lib=/usr/local/lib --with-xslt-dir=/usr/local
вторник, 24 ноября 2009 г.
MySQL gem на leopard 10.5...
среда, 11 ноября 2009 г.
Доступ к MSSQL из Rails (OS X Leopard)
Ruby/Rails => ActiveRecord SQL Server Adapter => DBI Gem w/DBD-ODBC => Ruby ODBC => unixODBC => FreeTDS => MSSQL Server.
Так как мне это нужно только для временого доступа к разным серверам то я использую проброс портов через ssh
$ ssh -L 1433:mssqlserver.mydomain:1433 login@myhostпоэтому вместо имени сервера я использую localhost
для начала ставим xcode с установочного диска и ports
или обновляем
$ sudo port selfupdateВсе настройки я описываю для ruby 1.8.7
Проверяем версию руби
$ ruby -vи обновляем при необходимости
$ sudo port install rubyставим gem
$ sudo port install rb-rubygemsтеперь переходим к установке unixODBC и FreeTDS
$ sudo port install unixODBCставим необходимые gem
$ sudo port install freetds +odbc
$ sudo gem install dbi -v 0.4.1на время написания статьи необходимо подправить Portfile для rb-odbc
$ sudo gem install dbd-odbc -v 0.2.4
$ sudo gem install activerecord-sqlserver-adapter
$ port file rb-odbc | xargs mateТеперь в открывшемся TextMate правим
0.9995 на 0.9997
и соответственно правим MD5 на 36d21519795c3edc8bc63b1ec6682b99
у меня получилось
# $Id: Portfile 30250 2007-10-23 02:16:17Z jmpp@macports.org $После сохранения файла можно ставить ruby ODBC
PortSystem 1.0
PortGroup ruby 1.0
ruby.setup {odbc ruby-odbc} 0.9997 extconf.rb {README doc test}
maintainers nomaintainer
description An extension library for ODBC from ruby.
long_description Extension library to use ODBC data sources from Ruby. \
Supports Ruby 1.6.x and 1.8 on Win32 OSes and UN*X
checksums md5 36d21519795c3edc8bc63b1ec6682b99
homepage http://www.ch-werner.de/rubyodbc
master_sites http://www.ch-werner.de/rubyodbc
categories-append databases
platforms darwin
variant utf8 {
configure.args-append -Cutf8
}
$ sudo port install rb-odbc +utf8Теперь настраиваем FreeTDS
$ mate /opt/local/etc/freetds/freetds.confя добавил в конец файла
[my_dev_server]После этого настраиваем unixODBC
host = localhost # я использую проброс портов
port = 1433
tds version = 8.0
port = 1433
client charset = UTF-8 # у меня серваки отдают win1251 а в рельсах utf-8
$ sudo cp /opt/local/etc/odbc.ini.dist /opt/local/etc/odbc.iniвставляем
$ sudo cp /opt/local/etc/odbcinst.ini.dist /opt/local/etc/odbcinst.ini
$ mate /opt/local/etc/odbcinst.ini
[FreeTDS]теперь очередь за настройкой DSN
Decscription = FreeTDS driver for SQLServer
Driver = /opt/local/lib/libtdsodbc.so
Setup = /opt/local/lib/libtdsodbc.so
FileUsage = 1
$ mate /opt/local/etc/odbc.iniвот например мой
[my_dev_server_dsn]теперь очередь за database.yml в приложении
Driver=FreeTDS
Description=My Server Connection
Servername=my_dev_server
Server=my_dev_server
Port=1433
Database=mssql-database
например
development-mssql:
adapter: sqlserver
mode: ODBC
username: user
password: secret
database: mssql-database # возможно достаточно настроек dsn
dsn: my_dev_server_dsn
Все работает.
На самом деле я использую модель и rake task для импорта данных в рельсовое приложение т.е. только на этапе разработки.
вторник, 7 июля 2009 г.
irb readline support on Leopard
Written March 22, 2008 at 22:40 CET. Tagged Ruby and OS X.
The irb
(Interactive Ruby) that ships with OS X Leopard does not have readline
support. Instead it uses libedit.
This means that things like ⌃R
for reverse history search don't work. More importantly to me, you can't use non-ASCII characters like Swedish "å", "ä" and "ö".
Compiling your own Ruby (with readline) is one solution. If you just want ctrl+R, macosxhints has another.
The solution I'm currently using is the work of jptix, a regular on the ##textmate IRC channel. He asked me to blog about it, so here it is.
Используем Google maps Directions
+ смотри plugin ym4r-gm
среда, 24 июня 2009 г.
Обновляем Ruby on rails на Leopard 10.5.6
gem outdate
sudo gem update --system
sudo gem update
если нужно ставим mysql и соответственно ставим гем
sudo env ARCHFLAG="=arch i386" gem install mysql --\--with-mysql-include=/usr/local/mysql/include \--with-mysql-lib=/usr/local/mysql/libдля sqlite3
sudo env ARCHFLAGS="-arch i386" gem install sqlite3-ruby
пятница, 29 мая 2009 г.
Ruby → Настрой собственный VPS в течение обеденного перерыва!
обозначу несколько принципиальных вещей:
1) системное администрирование -- в 80% случаев -- тривиальные задачи,
ответ на которые ждут вас на первой странице поисковой системы
2) настройка удаленного сервера принципиально ничем не отличается от
конфигурирования рабочей станции. настраивать последюнюю приходится
каждому из нас, согласитесь -- занятие приятное и довольно простое
3) благодаря высокой популярности vps, вероятность того, что вы
окажетесь в тупике по любому вопросу -- ничтожна мала
sudo apt-get -y install build-essential libssl-dev libreadline5-dev
zlib1g-dev vim wget curl
sudo apt-get -y install mysql-server libmysqlclient15-dev mysql-client
adduser demo
visudo (demo ALL=(ALL) ALL)
---SSH (local pc)------------
mkdir ~/.ssh
ssh-keygen -t rsa
scp ~/.ssh/id_rsa.pub d...@12.12.12.12:~
---SSH (remote pc)-----------
mkdir /home/demo/.ssh
mv /home/demo/id_rsa.pub /home/demo/.ssh/authorized_keys
chown -R demo:demo /home/demo/.ssh
chmod 700 /home/demo/.ssh
chmod 600 /home/demo/.ssh/authorized_keys
---locales-----------------------
sudo locale-gen en_GB.UTF-8
sudo /usr/sbin/update-locale LANG=en_GB.UTF-8
---Ruby ----Passenger------------
mkdir ~/temp && cd ~/temp
wget rubyforge.org/frs/download.php/57097/ruby-
enterprise-1.8.6-20090520.tar.gz
tar xzvf ruby-enterprise-1.8.6-20090520.tar.gz
sudo ./ruby-enterprise-1.8.6-20090520/installer
export PATH=/opt/ruby-enterprise-1.8.6-20090520/bin:$PATH
sudo /opt/ruby_ee/bin/passenger-install-nginx-module
---Nginx-------------------------
sudo useradd -s /sbin/nologin -r www-data
sudo usermod -a -G www-data demo
mkdir ~/public_html
mkdir ~/public_html/01_project
sudo su
chgrp -R www-data ~/public_html/
chmod -R 2750 ~/public_html/
mkdir /opt/nginx/sites-available
mkdir /opt/nginx/sites-enabled
wget railsgeek.com/vps/vhost01 -P /opt/nginx/sites-available
ln -s /opt/nginx/sites-available/vhost01 /opt/nginx/sites-enabled
wget railsgeek.com/vps/nginx.conf -P /opt/nginx/conf
wget railsgeek.com/vps/nginx -P /etc/init.d
chmod +x /etc/init.d/nginx
/etc/init.d/nginx start
http://habrahabr.ru/blogs/ruby/60676/
понедельник, 9 февраля 2009 г.
установка ruby on Rails в Ubuntu 8.10
# General/Pre-requisite packages
aptitude install \
build-essential \
screen \
subversion \
mysql-client \
telnet \
meld \
vim \
vim-gnome \
exuberant-ctags \
tk8.5 \
apache2-prefork-dev \
rcov
# mysql server
# use apt-get to avoid installing exim4
DEBIAN_FRONTEND=noninteractive apt-get install --assume-yes \
mysql-server mysql-client \
libmysqlclient15-dev libmysql-ruby1.8
# git
mkdir gitcore
cd gitcore
wget http://kernel.org/pub/software/scm/git/git-1.6.0.3.tar.gz
apt-get build-dep git-core --assume-yes
tar xzvf git-1.6.0.3.tar.gz
cd git-1.6.0.3/
./configure
make
make install
cd
# Ruby
aptitude --assume-yes install ruby1.8-dev ruby1.8 ri1.8 rdoc1.8 \
irb1.8 libreadline-ruby1.8 libruby1.8 libopenssl-ruby
ln -s /usr/bin/ruby1.8 /usr/local/bin/ruby;
ln -s /usr/bin/ri1.8 /usr/local/bin/ri;
ln -s /usr/bin/rdoc1.8 /usr/local/bin/rdoc;
ln -s /usr/bin/irb1.8 /usr/local/bin/irb;
ln -s /usr/local/bin/ruby /usr/bin/ruby
# Rubygems. You REALLY don't want to let aptitude install rubygems.
wget http://rubyforge.org/frs/download.php/45905/rubygems-1.3.1.tgz
cd rubygems-1.3.1
ruby setup.rb
ln -s /usr/bin/gem1.8 /usr/bin/gem
for g in rails rake capistrano capistrano-ext hpricot treetop ruby-debug term-ansicolor mongrel cheat passenger annotate-models rak; do gem install $g; done