Showing posts with label Rails. Show all posts
Showing posts with label Rails. Show all posts

Saturday, July 02, 2011

rails 3.0.7 在ubuntu 11.04中安装问题


$> sudo gem install rails

This is the problematic part:

File not found: lib
ERROR: While generating documentation for rails-3.0.7
... MESSAGE: exit
...

这个问题是因为Rails新版本使用了最新的Rdoc/ri版本,而系统中原来的版本有些功能不是兼容的,因此报错。
卸载已经安装的rails3,先安装rdoc-data成功后再安装rails3。

$> sudo gem uninstall rails --version 3.0.7
$> sudo gem install rdoc-data
$> sudo rdoc-data --install
$> sudo gem install rails

安装成功信息:
Successfully installed rails-3.0.7
1 gem installed
Installing ri documentation for rails-3.0.7...
Installing RDoc documentation for rails-3.0.7...

Monday, May 24, 2010

rails session options

require 'action_controller/cgi_ext'
require 'action_controller/session/cookie_store'

module ActionController #:nodoc:
class Base
# Process a request extracted from a CGI object and return a response. Pass false as session_options to disable
# sessions (large performance increase if sessions are not needed). The session_options are the same as for CGI::Session:
#
# * :database_manager - standard options are CGI::Session::FileStore, CGI::Session::MemoryStore, and CGI::Session::PStore
# (default). Additionally, there is CGI::Session::DRbStore and CGI::Session::ActiveRecordStore. Read more about these in
# lib/action_controller/session.
# * :session_key - the parameter name used for the session id. Defaults to '_session_id'.
# * :session_id - the session id to use. If not provided, then it is retrieved from the +session_key+ cookie, or
# automatically generated for a new session.
# * :new_session - if true, force creation of a new session. If not set, a new session is only created if none currently
# exists. If false, a new session is never created, and if none currently exists and the +session_id+ option is not set,
# an ArgumentError is raised.
# * :session_expires - the time the current session expires, as a Time object. If not set, the session will continue
# indefinitely.
# * :session_domain - the hostname domain for which this session is valid. If not set, defaults to the hostname of the
# server.
# * :session_secure - if +true+, this session will only work over HTTPS.
# * :session_path - the path for which this session applies. Defaults to the directory of the CGI script.
# * :cookie_only - if +true+ (the default), session IDs will only be accepted from cookies and not from
# the query string or POST parameters. This protects against session fixation attacks.
def self.process_cgi(cgi = CGI.new, session_options = {})
new.process_cgi(cgi, session_options)
end

def process_cgi(cgi, session_options = {}) #:nodoc:
process(CgiRequest.new(cgi, session_options), CgiResponse.new(cgi)).out
end
end

end

Monday, March 01, 2010

Ctags for rails and gvim

ctags支持41种语言,常见的 JAVA/C/C++/JavaScript/PHP/Perl/Python/Ruby等都包括其中,更多信息可查看官网和帮助手册。

在ubuntu中安装ctags:

$> sudo apt-get install exuberant-ctags


在rails项目下生成ctags文件,生成的TAGS文件可以用于vim/emacs等编辑器:
$> ctags-exuberant -a -e -f TAGS --tag-relative -R app lib vendor /opt/ruby-enterprise/lib/ruby/gems/1.8/gems


在gvim中常的操作有以下4个:
$> gvim −t tag

打开定义 tag 的文件。

在vi中使用:ta tag打开定义tag的文件
:ta tag


在vi的指针位置打开定义所在tag的文件
Ctrl-]


回退到之前的位置
Ctrl-T

Debugging rails with ruby-debug

1. setup
$> sudo gem install ruby-debug

2. start rails webrick/mongrel web server
$> script/server --debugger

3. using debugger in controller

class PeopleController < ApplicationController def new debugger # 当应用程序访问到此行时,在console中会出现debugger控制台 @person = Person.new end end

4. debugger shell 命令帮助
(rdb:40) help
ruby-debug help v0.10.3
Type 'help ' for help on a specific command

Available commands:
backtrace delete enable help next quit show
break disable eval info p reload source
catch display exit irb pp restart step
condition down finish list ps save thread
continue edit frame method putl set trace

其中比较常用的是next/list/continue/method/backtrace命令。

更多关于ruby-debug,查看以下链接:
http://articles.sitepoint.com/article/debug-rails-app-ruby-debug
http://guides.rubyonrails.org/debugging_rails_applications.html

Monday, September 07, 2009

Helpers Outside Views

How to access helper methods outside of the view layer?


# models/category.rb
def description
  "This category has #{helpers.pluralize(products.count, 'product')}."
end

def helpers
  ActionController::Base.helpers
end

# products_controller.rb
def create
  @product = Product.new(params[:product])
  if @product.save
    flash[:notice] = "Successfully created #{@template.link_to('product', @product)}."
    redirect_to products_url
  else
    render :action => 'new'
  end
end


Reference: http://railscasts.com/episodes/132-helpers-outside-views

Thursday, January 08, 2009

stack level too deep in will_paginate

After update rails from 1.2.5 to 2.2.2, get below exception:
stack level too deep
../vendor/plugins/will_paginate/lib/will_paginate/finder.rb:81:in `method_missing_without_paginate'
../vendor/plugins/will_paginate/lib/will_paginate/finder.rb:82:in `method_missing'

solution, update will_paginate:
$> script/plugin install git://github.com/mislav/will_paginate.git

Tuesday, January 06, 2009

Rails module include way

# Rails module include way
# 以下方式的代码在rails中源码中的相当多见,其中的self.included(base)方法是一个回调方法,当此module被其他名为base的module(或者class)include的时候触发此方法。通过class_eval,include,extend加入了实例方法和类方法到base中,代码划分得很干净。

module ActionController
module Components
def self.included(base)
base.class_eval do
include InstanceMethods
extend ClassMethods
helper HelperMethods
end
end

module ClassMethods
end

module HelperMethods
end

module InstanceMethods
end
end
end

Monday, December 22, 2008

在ubuntu 8.10 上安装passenger 2.0.6

按照http://www.rubyenterpriseedition.com/download.html#ubuntu上的说明,在ubuntu8.10上安装passenger时报以下错误:
Welcome to the Phusion Passenger Apache 2 module installer, v2.0.6.

This installer will guide you through the entire installation process. It
shouldn't take more than 3 minutes in total.

Here's what you can expect from the installation process:

1. The Apache 2 module will be installed for you.
2. You'll learn how to configure Apache.
3. You'll learn how to deploy a Ruby on Rails application.

Don't worry if anything goes wrong. This installer will advise you on how to
solve any problems.

Press Enter to continue, or Ctrl-C to abort.

Checking for required software...

* GNU C++ compiler... found at /usr/bin/g++
* Ruby development headers... found
* OpenSSL support for Ruby... found
* RubyGems... found
* Rake... found at /opt/ruby-enterprise/bin/rake
* Apache 2... found at /usr/sbin/apache2
* Apache 2 development headers... found at /usr/bin/apxs2
* Apache Portable Runtime (APR) development headers... found at /usr/bin/apr-1-config
* Apache Portable Runtime Utility (APR) development headers... found at /usr/bin/apu-1-config
* fastthread... found
* rack... found
--------------------------------------------

--------------------------------------------
Compiling and installing Apache 2 module...
cd /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/passenger-2.0.6
/opt/ruby-enterprise/bin/ruby -S rake clean apache2
/usr/bin/rake:27:in `require': no such file to load -- rake (LoadError)
from /usr/bin/rake:27

--------------------------------------------
It looks like something went wrong

Please read our Users guide for troubleshooting tips:

/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/passenger-2.0.6/doc/Users guide.html

If that doesn't help, please use our support facilities at:

http://www.modrails.com/

We'll do our best to help you.

在/usr/bin/rake文件的27行前加上一句:
require 'rubygems'
重新运行passenger命令就可以正确安装上。
ubuntu 8.10中原来已经安装了ruby 1.8.7,与ruby-enterprise中的ruby版本不一样,需要在用户根目录下的.bashrc文件中调整一下PATH:
export PATH=/opt/ruby-enterprise/bin:$PATH

另外系统中sudo没有gem命令,需要加个软链接,这样才能用sudo安装gem包:
$> sudo ln -s /opt/ruby-enterprise/bin/gem /usr/bin/gem
(不要用sudo apt-get install rubygems 安装)

之后再生成二个文件:
$> sudo vi /etc/apache2/conf.d/rails
LoadModule passenger_module /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/passenger-2.0.6/ext/apache2/mod_passenger.so
PassengerRoot /opt/ruby-enterprise/lib/ruby/gems/1.8/gems/passenger-2.0.6
PassengerRuby /opt/ruby-enterprise/bin/ruby
RailsEnv development
RailsDefaultUser test

$> sudo vi /etc/apache2/sites-enabled/rails_app
<VirtualHost *:80>
ServerName www.yourhost.com
DocumentRoot /somewhere/public
</VirtualHost>

重启apache2之后访问www.yourhost.com.

Tuesday, December 16, 2008

rails error ActionController::InvalidAuthenticityToken

升级到Rails 2.2.2后,在用户登录时抛出以上错误,因为Rails新版本对安全控制做了一些加强措施,只要在form中添加<%= token_tag %>即可,Rails会添加一个token(在action中的form_authenticity_token方法生成这个token)在form中,随表单一起提交,可以适当的防止一些web攻击。
<input name="authenticity_token" type="hidden" value="d688e6bf60f43bd171504e059de1ba03f876d129" />
具体可参考 ActionController::RequestForgeryProtection 和 config/environment.rb 中的配置说明:
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_sv3_session',
:secret => 'b35a7a9ffb88288f11c03b0c24fe45f90879d8fbb83f9ba70649b489d8165f06d4484dd07c6e41c2d9616630781fd739a127d1285c589db3d77801afd30a9d35'
}

Monday, December 15, 2008

mongrel and rails 2.2.2 环境下报 mysql lib 的错误及解决方法

Processing Rails::InfoController#properties (for 127.0.0.1 at 2008-12-15 17:10:53) [GET]

LoadError (dlopen(/Library/Ruby/Site/1.8/universal-darwin9.0/mysql.bundle, 9): Library not loaded: /usr/local/mysql/lib/libmysqlclient.15.dylib
Referenced from: /Library/Ruby/Site/1.8/universal-darwin9.0/mysql.bundle
Reason: image not found - /Library/Ruby/Site/1.8/universal-darwin9.0/mysql.bundle):
/Library/Ruby/Site/1.8/universal-darwin9.0/mysql.bundle
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require'
/Library/Ruby/Gems/1.8/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:153:in `require'

在MAC OSX 10.5 和 mysql 5.1.23-rc 上,rails 2.2.2 用 mongrel server 启动时访问首页mysql连接属性时抛出以上错误,在对应的/usr/local/mysql/lib下根本没有/usr/local/mysql/lib/libmysqlclient.15.dylib这个文件,当然会加载失败,之前在 rails 2.0.2 上倒没有碰到过这个问题。从mysql官网重新下载了一个 mysql 5.0.67,从其下面拷了一个libmysqlclient.15.dylib 到 /usr/local/mysql/lib/libmysqlclient.15.dylib,就可以解决此问题。
$> sudo cp /usr/local/mysql5/lib/libmysqlclient.15.dylib /usr/local/mysql/lib/libmysqlclient.15.dylib

Saturday, August 30, 2008

MySQL 数据库字符集问题

在rails项目开发中碰到一个MySQL数据库字符集问题 ,一个DEFAULT CHARSET utf8的数据库中,有一个ENGINE=MyISAM DEFAULT CHARSET=utf8的数据表,手工往其中插入中文,日文,韩文都没有问题,但通过rails添加数据记录时,中文,日文没有问题,但是插入韩文就一直乱码,rails和手工执行的sql相同,如下所示:


set names utf8;
insert TableName values('', '시험');

网上查不到什么相关资料,在rails中做了一些测试性的调整,都没有解决问题。最后决定调整mysql server的默认字符集,虽然觉得这个应该不会造成rails无法插入韩文,因为在rails中加过before_save前置过滤器,在其中先运行"set names utf8;",之后再执行insert操作,也一样是乱码。
在my.cnf中加入如下配置并重启mysql服务之后,rails就可以正常插入韩文了!!

# The MySQL server
[mysqld]
character-set-server = utf8


另摘录一段mysql server启动的参数选项说明:
·         --character-set-server=charset
使用charset作为 默认服务器字符
·         --collation-server=collation
使用collation作为 默认服务器校对规则
·         (DEPRECATED) --default-character-set=charset
使用char设置作为 默认字符集。由于--character-set-server,反对使用该选项。
·         --default-collation=collation
使用collation 作为默认校对规则。由于--collation-server,反对使用该选项。

Thursday, July 31, 2008

Rails Plugins 相关命令

$> script/plugin -h


Usage: plugin [OPTIONS] command
Rails plugin manager.

GENERAL OPTIONS
-r, --root=DIR Set an explicit rails app directory.
Default: /Users/yu/Sites/docbox
-s, --source=URL1,URL2 Use the specified plugin repositories instead of the defaults.
-v, --verbose Turn on verbose output.
-h, --help Show this help message.

COMMANDS
discover Discover plugin repositories.
list List available plugins.
install Install plugin(s) from known repositories or URLs.
update Update installed plugins.
remove Uninstall plugins.
source Add a plugin source repository.
unsource Remove a plugin repository.
sources List currently configured plugin repositories.

EXAMPLES
Install a plugin:
plugin install continuous_builder

Install a plugin from a subversion URL:
plugin install http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder

Install a plugin from a git URL:
plugin install git://github.com/SomeGuy/my_awesome_plugin.git

Install a plugin and add a svn:externals entry to vendor/plugins
plugin install -x continuous_builder

List all available plugins:
plugin list

List plugins in the specified repository:
plugin list --source=http://dev.rubyonrails.com/svn/rails/plugins/

Discover and prompt to add new repositories:
plugin discover

Discover new repositories but just list them, don't add anything:
plugin discover -l

Add a new repository to the source list:
plugin source http://dev.rubyonrails.com/svn/rails/plugins/

Remove a repository from the source list:
plugin unsource http://dev.rubyonrails.com/svn/rails/plugins/

Show currently configured repositories:
plugin sources

Juggernaut for Rails 启动报错

07/31/08 18:00:18 INFO Starting up on 0.0.0.0:443...
/Library/Ruby/Gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:500:in `start_tcp_server': no acceptor (RuntimeError)
from /Library/Ruby/Gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:500:in `start_server'
from script/push_server:216
from /Library/Ruby/Gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:224:in `call'
from /Library/Ruby/Gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:224:in `run_machine'
from /Library/Ruby/Gems/1.8/gems/eventmachine-0.12.0/lib/eventmachine.rb:224:in `run'

google后,才发现在mac上用普通用户去使用443这个1024以下的系统使用端口号,因为权限问题才导致服务无法成功启动。

Thursday, April 24, 2008

rails2.0.2 fastcgi sqlite3 setup

# add below line to /etc/hosts
127.0.0.1 www.test.com

# add below green lines at the end of lighttpd.conf file


$HTTP["host"] == "www.test.com" {
server.document-root = "/Users/test/Sites/RubyOnRails/public"
server.errorlog = "/Users/test/Sites/lighttpd/logs/rails.lighttpd.error.log"
server.indexfiles = ( "dispatch.fcgi", "index.html" )
accesslog.filename = "/Users/test/Sites/lighttpd/logs/rails.access.log"
server.error-handler-404 = "/dispatch.fcgi"
fastcgi.server = ( ".fcgi" =>
( "localhost" =>
(
"socket" => "/tmp/rails-fastcgi.socket",
"bin-path" => "/Users/test/Sites/RubyOnRails/public/dispatch.fcgi",
"bin-environment" => ("RAILS_ENV" => "development"),
"max-procs" => 3,
"min-procs" => 1
)
)
)
}

wget http://www.sqlite.org/sqlite-3.5.8.tar.gz
tar zxvf sqlite-3.5.8.tar.gz
cd sqlite-3.5.8
./configure --prefix=/usr/local/sqlite358
make
sudo make install

# create db files under rails app db folder
cd /Users/test/Sites/RubyOnRails/db
/usr/local/sqlite358/bin/sqlite3 development.sqlite3
/usr/local/sqlite358/bin/sqlite3 test.sqlite3
/usr/local/sqlite358/bin/sqlite3 production.sqlite3

sudo gem install sqlite3-ruby

# restart lighttpd, and request url: http://www.test.com

Monday, April 07, 2008

ActiveRecord::Base transaction explain


#---
# Excerpted from "Agile Web Development with Rails, 2nd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails2 for more book information.
#---
# $: << File.dirname(__FILE__)

require "logger"
require "rubygems"
require "active_record"

ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:user => "root",
:password => "",
:database => "test"
)

# InnoDB table: users, accounts
ActiveRecord::Schema.define do

create_table :accounts, :force => true do |t|
t.column :number, :string
t.column :balance, :decimal, :precision => 10, :scale => 2, :default => 0
end

create_table :users, :force => true do |t|
t.column :name, :string
t.column :password, :string
end

end

class User < ActiveRecord::Base
end

class Account < ActiveRecord::Base
end

Account.transaction do
Account.create(:balance => 100, :number => "12345")
User.create(:name => 'test', :password => "123456")
raise 'error!!!'
# 如果transaction内部所有SQL都正确执行并且通过ActiveRecord::Base validates,在block中没有raise的话则正确写入数据库
# 如果有SQL错误或者validates没有通过,或者是transaction中有raise错误,则事务会ROLLBACK
# ROLLBACK 是基于事务表(如InnoDB表)的,非事务表(如MyISAM表)则需要在程序中手工回滚
end

Tuesday, April 01, 2008

Rails Content type header setting

Added utf-8 as the default charset for all renders. You can change this default using:
ActionController::Base.default_charset=(encoding) [DHH]
...now:
config.action_controller.default_charset="utf-8"

Added proper getters and setters for content type and charset [DHH]. Example of what we used to do:
response.headers["Content-Type"] = "application/atom+xml; charset=utf-8"

...now:
response.content_type = Mime::ATOM
response.charset = "utf-8"

Tuesday, March 18, 2008

[rails api]filter_parameter_logging API usage

Class ActionController::Base

filter_parameter_logging(*filter_words) {|key, value| ...}
Replace sensitive paramater data from the request log. Filters paramaters that have any of the arguments as a substring. Looks in all subhashes of the param hash for keys to filter. If a block is given, each key and value of the paramater hash and all subhashes is passed to it, the value or key can be replaced using String#replace or similar method.

Examples:

filter_parameter_logging
=> Does nothing, just slows the logging process down

filter_parameter_logging :password
=> replaces the value to all keys matching /password/i with "[FILTERED]"

filter_parameter_logging :foo, "bar"
=> replaces the value to all keys matching /foo|bar/i with "[FILTERED]"

filter_parameter_logging { |k,v| v.reverse! if k =~ /secret/i }
=> reverses the value to all keys matching /secret/i

filter_parameter_logging(:foo, "bar") { |k,v| v.reverse! if k =~ /secret/i }
=> reverses the value to all keys matching /secret/i, and
replaces the value to all keys matching /foo|bar/i with "[FILTERED]"

Friday, February 22, 2008

Cleaning up rails old session file

$> cd rails_app
$> find tmp/sessions/ruby_sess* -ctime +2 | xargs rm -f

参数说明:
-ctime n: 文件修改时间n*24小时,+2即文件最后修改时间大于2天,此session已经过期。
xargs command: 执行命令。

Thursday, February 21, 2008

[Rails Cookbook Recipe 10.2] Fixing Bugs at the Source with Ruby -cw

Using the syntax checker is a great way to make sure you're supplying Rails with valid Ruby, and it's easy enough to do every time you save a file. If you're using any modern programmable text editor, you should be able to check syntax without leaving your program. For example, while editing the solution's student.rb file in Vim, you can type :w !ruby -cw in command mode, and you'll see the following within the editor:


:w !ruby -cw
-:4: parse error, unexpected '}', expecting kEND
Student.find(:all).map {|s| s.age }}.flatten.uniq.sort
^

shell returned 1

Hit ENTER or type command to continue

If you're using TextMate on a Mac, you can set up a keyboard shortcut that filters the file you're working on through a command such as ruby -cw. If you're not using a text editor or IDE that offers this kind of flexibility, you should consider switching to something like Vim, TextMate, or Emacs, and learning how to customize your editor.