履歴: ソフトウェア/rails/言語ネゴシエーション
各行は、その日時に書かれた内容です。追加・削除は、1 つ前の版との行数の差です (全 21 版)。「差分」は比較する版、「基準」は比べる相手の版を選びます
| 日時 | タイトル | 文字数 | 追加 | 削除 | 内容 | 差分 | 基準 |
|---|---|---|---|---|---|---|---|
| 2014/5/20 19:20:23 | ソフトウェア/rails/言語ネゴシエーション 最新版 | 3,891 | +1 | -1 | 表示 | 差分 | — |
| 2014/5/20 19:20:23 | ソフトウェア/rails/言語ネゴシエーション | 3,897 | +8 | -1 | 表示 | 差分 | 選択 |
| 2013/1/5 18:30:15 | ソフトウェア/rails/言語ネゴシエーション | 3,842 | +3 | -0 | 表示 | 差分 | 選択 |
| 2009/7/14 9:35:50 | ソフトウェア/rails/言語ネゴシエーション | 3,732 | +43 | -27 | 表示 | 差分 | 選択 |
| 2009/7/11 15:06:20 | ソフトウェア/rails/言語ネゴシエーション | 3,727 | +9 | -0 | 表示 | 差分 | 選択 |
| 2009/6/28 2:02:38 | ソフトウェア/rails/言語ネゴシエーション | 3,515 | +2 | -0 | 表示 | 差分 | 選択 |
| 2009/6/27 8:15:42 | ソフトウェア/rails/言語ネゴシエーション | 3,458 | +4 | -0 | 表示 | 差分 | 選択 |
| 2009/6/21 9:14:00 | ソフトウェア/rails/言語ネゴシエーション | 3,403 | +15 | -0 | 表示 | 差分 | 選択 |
| 2009/6/21 6:41:27 | ソフトウェア/rails/言語ネゴシエーション | 3,126 | +62 | -2793 | 表示 | 差分 | 選択 |
| 2009/6/10 11:14:13 | ソフトウェア/rails/言語ネゴシエーション | 84,051 | +327 | -1 | 表示 | 差分 | 選択 |
| 2009/6/10 3:14:21 | ソフトウェア/rails/言語ネゴシエーション | 73,730 | +459 | -3 | 表示 | 差分 | 選択 |
| 2009/6/9 15:42:54 | ソフトウェア/rails/言語ネゴシエーション | 58,379 | +247 | -473 | 表示 | 表示中 | 選択 |
| 2009/6/9 11:29:37 | ソフトウェア/rails/言語ネゴシエーション | 66,074 | +317 | -40 | 表示 | 差分 | 選択 |
| 2009/6/8 20:22:16 | ソフトウェア/rails/言語ネゴシエーション | 58,607 | +75 | -2 | 表示 | 差分 | 選択 |
| 2009/6/8 15:18:39 | ソフトウェア/rails/言語ネゴシエーション | 55,917 | +958 | -223 | 表示 | 差分 | 基準 |
| 2009/6/8 8:00:44 | ソフトウェア/rails/言語ネゴシエーション | 33,858 | +247 | -35 | 表示 | 差分 | 選択 |
| 2009/6/7 13:55:06 | ソフトウェア/rails/言語ネゴシエーション | 28,314 | +195 | -18 | 表示 | 差分 | 選択 |
| 2009/6/7 4:15:30 | ソフトウェア/rails/言語ネゴシエーション | 23,332 | +140 | -3 | 表示 | 差分 | 選択 |
| 2009/6/6 14:50:13 | ソフトウェア/rails/言語ネゴシエーション | 19,622 | +30 | -27 | 表示 | 差分 | 選択 |
| 2009/6/6 6:50:47 | ソフトウェア/rails/言語ネゴシエーション | 19,701 | +581 | -3 | 表示 | 差分 | 選択 |
| 2009/6/6 2:59:56 | ソフトウェア/rails/言語ネゴシエーション | 2,869 | — | — | 表示 | — | 選択 |
基準: ソフトウェア/rails/言語ネゴシエーション (2009/6/8 15:18:39) → 比較: ソフトウェア/rails/言語ネゴシエーション (2009/6/9 15:42:54)
@@ -10,7 +10,7 @@
rails アプリケーションの多言語化する方法を調べてみた。
rails のバージョンが上がっているせいと、それ以外の問題とで、
-結局かなりの部分を1から書いたのでメモメモ。
+結局かなりの部分を1から書いたのでメモしておく。
やりたい内容としては
+ views/*/*.html.ja.erb と views/*/*.html.en.erb とを両方作っておき、
@@ -91,7 +91,7 @@
Action Mailer version 2.2.2
Active Support version 2.2.2
Edge Rails revision unknown
- Application root /home/samba/www/rails/negotiation
+ Application root (rails)/negotiation
Environment development
Database adapter sqlite3
Database schema version 0
@@ -936,12 +936,12 @@
日本語: テスト ばっちり
$ tail /var/log/apache2/rewrite.log
- [perdir /home/samba/www/negotiation/] pass through /home/samba/www/negotiation/test.html.ja
+ [perdir (DOCROOT)/negotiation/] pass through (DOCROOT)/negotiation/test.html.ja
$ wgetc http://localhost/negotiation/test.ja
日本語: テスト ばっちり
$ tail /var/log/apache2/rewrite.log
- [perdir /home/samba/www/negotiation/] pass through /home/samba/www/negotiation/dispatch.cgi
+ [perdir (DOCROOT)/negotiation/] pass through (DOCROOT)/negotiation/dispatch.cgi
$ wget -O- --header="Accept-Language: en" http://localhost/negotiation/test
エラー 406: Not Acceptable
$ wgetc http://localhost/negotiation/test.en
@@ -953,7 +953,7 @@
日本語: テスト ばっちり
$ tail /var/log/apache2/rewrite.log
- [perdir /home/samba/www/negotiation/] pass through /home/samba/www/negotiation/test.html.ja
+ [perdir (DOCROOT)/negotiation/] pass through (DOCROOT)/negotiation/test.html.ja
$ wget -qO- --header="Accept-Language: en" http://localhost/negotiation/test
English: Test OK
@@ -1162,7 +1162,7 @@
English: Test OK
$ tail /var/log/apache2/rewrite.log
- initial URL equal rewritten URL: /home/samba/www/negotiation/test.html.en
+ initial URL equal rewritten URL: (DOCROOT)/negotiation/test.html.en
$ wget -qO- --header="Accept: text/html" --header="Accept-Language: ja" http://localhost/negotiation/test
日本語: テスト ばっちり
@@ -1172,10 +1172,10 @@
日本語: テスト ばっちり
$ tail /var/log/apache2/rewrite.log
- initial URL equal rewritten URL: /home/samba/www/negotiation/test.html.ja
+ initial URL equal rewritten URL: (DOCROOT)/negotiation/test.html.ja
$ wget -qO- --header="Accept: text/html" --header="Accept-Language: en" http://localhost/negotiation/test
$ tail /var/log/apache2/rewrite.log
- initial URL equal rewritten URL: /home/samba/www/negotiation/test.html.en
+ initial URL equal rewritten URL: (DOCROOT)/negotiation/test.html.en
$ rm public/test*
$ wget -qO- --header="Accept: text/html" http://localhost/negotiation/test.ja
日本語: テスト ばっちり
@@ -1186,7 +1186,7 @@
日本語: テスト ばっちり
$ tail /var/log/apache2/rewrite.log
- initial URL equal rewritten URL: /home/samba/www/negotiation/test.html.ja
+ initial URL equal rewritten URL: (DOCROOT)/negotiation/test.html.ja
$ wget -qO- --header="Accept: text/html" http://localhost/negotiation/test.en
English: Test OK
@@ -1434,405 +1434,6 @@
うまく行っているようだ。
-* ここまでのコード [#o65761f9]
-
-以下にここまでのコードをまとめておく。
-
-public/.htaccess
- LANG:shell(linenumber)
- # rails setting
- SetEnv RAILS_RELATIVE_URL_ROOT /negotiation
- SetEnv RAILS_ENV production
- SetEnv RAILS_ACCEPTABLE_LANGUAGES ja|en
-
- # save preferential language in cookie
- SetEnvIf Cookie "rails_language=([a-z][a-z])" prefer-language=$1
-
- # avoid error due to cache miss
- LanguagePriority ja en
- ForceLanguagePriority Prefer Fallback
-
- # rewrite start
- RewriteEngine On
-
- # default format of ".html"
- RewriteCond %{HTTP_ACCEPT} html
- RewriteCond %{SCRIPT_FILENAME} !\.html\.
- RewriteCond %{SCRIPT_FILENAME} (.*)\.([a-z][a-z])$
- RewriteCond %1.html.%2 -f
- RewriteRule (.*)\.([a-z][a-z])$ $1.html.$2 [L]
-
- # rails' default rules
- RewriteRule ^$ index.html [QSA]
- RewriteRule ^([^.]+)$ $1.html [QSA]
- RewriteCond %{REQUEST_FILENAME} !-f
- # change this to adapt to your server
- RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
-
- # detect cache miss for prefer-language
- RewriteCond %{ENV:prefer-language} ^[a-z][a-z]$
- RewriteCond %{ENV:prefer-language} !=$2
- RewriteRule (.*\.html\.)([a-z][a-z]) $1%{ENV:prefer-language} [L]
-
- # detect cache miss for accept-language
- # omit this section if performance matters
- RewriteCond %{HTTP:Accept-Language} !$2 [NC]
- RewriteCond %{HTTP:Accept-Language} ([a-z][a-z])
- RewriteRule (.*\.html\.)([a-z][a-z]) $1%1
-
-config/routes.rb
- LANG:ruby(linenumber)
- ENV['RAILS_ACCEPTABLE_LANGUAGES'] ||= 'ja|en'
-
- ActionController::Routing::Routes.draw do |map|
-
- lang_regexp= Regexp.new( ENV['RAILS_ACCEPTABLE_LANGUAGES'] )
-
- map.connect ':controller.:rails_language', :format => 'html', :action => 'index',
- :requirements => { :rails_language => lang_regexp }
- map.connect ':controller/:action.:rails_language', :format => 'html',
- :requirements => { :rails_language => lang_regexp }
- map.connect ':controller/:action/:id.:rails_language', :format => 'html',
- :requirements => { :rails_language => lang_regexp }
- map.connect ':controller/:action/:id', :format => 'html'
-
- map.connect ':controller/:action/:id.:format.:rails_language',
- :requirements => { :rails_language => lang_regexp }
- map.connect ':controller/:action/:id.:format',
- :defaults => { :action => 'index', :format => 'html' }
-
- end
-
-config/environment.rb
- LANG:ruby(linenumber)
- #### acceptable languages
-
- class ActionController::AbstractRequest
-
- def self.acceptable_languages
- @acceptable_languages ||=
- ENV['RAILS_ACCEPTABLE_LANGUAGES'].split('|').map {|l| l.to_sym}
- end
-
- def self.acceptable_language?(l)
- acceptable_languages.include?(l.to_sym)
- end
-
- end
-
- #### language preference order
-
- class ActionController::AbstractRequest
-
- # will be set by ActionView::Base._pick_template
- attr :language, true
-
- def accepts_languages!(language=nil)
- @accepts_languages= [
- language ? language.to_sym : nil,
- ( cookie = cookies['rails_language'] and l = cookie.first and
- ActionController::AbstractRequest.acceptable_language?(l) ) ? l.to_sym : nil,
- ( @env['HTTP_ACCEPT_LANGUAGE'] || '' ).split(",").collect {|l|
- lsym= l.split(/;|\-/,2)[0].downcase.to_sym
- ActionController::AbstractRequest.acceptable_language?(lsym) ? lsym : nil
- },
- ActionController::AbstractRequest.acceptable_languages
- ].flatten.compact.uniq
- end
-
- def accepts_languages
- @accepts_languages || accepts_languages!
- end
-
- end
-
- #### store specified language into cookie
-
- class ActionController::Base
-
- # before_filter :set_language
- # fails for some unknown reason.
- # following is a workaround.
-
- def perform_action_with_set_rails_language
- set_rails_language
- perform_action_without_set_rails_language
- end
- alias_method_chain :perform_action, :set_rails_language
-
- def set_rails_language
- rails_language= params[:rails_language]
- if rails_language && ActionController::AbstractRequest.acceptable_language?(rails_language)
- cookies['rails_language']= { :value => rails_language }
- request.accepts_languages!(rails_language)
- end
- end
- end
-
- #### unmemoize
-
- module ActiveSupport::Memoizable
-
- def memoized?(symbol)
- original_method = :"_unmemoized_#{symbol}"
- class_eval <<-EOS, __FILE__, __LINE__
- method_defined?(:#{original_method})
- EOS
- end
-
- def unmemoize(*symbols)
- symbols.each do |symbol|
- original_method = :"_unmemoized_#{symbol}"
- memoized_ivar = MEMOIZED_IVAR.call(symbol)
- class_eval <<-EOS, __FILE__, __LINE__
- raise "Not memoized #{symbol}" if !method_defined?(:#{original_method})
- alias #{symbol} #{original_method}
- undef #{original_method}
- #{memoized_ivar}= nil
- EOS
- end
- end
-
- end
-
- #### to pick language-specific templates
-
- class ActionView::Base
-
- private
-
- def _pick_template_sub(template_file_name, lang="")
- if template = self.view_paths["#{template_file_name}.#{template_format}#{lang}"]
- return template
- elsif template = self.view_paths["#{template_file_name}#{lang}"]
- return template
- elsif (first_render = @_render_stack.first) && first_render.respond_to?(:format_and_extension)
- m= first_render.format_and_extension.match(/(.*)(\.\w+)?$/)
- template = self.view_paths["#{template_file_name}.#{m[1]}#{lang}#{m[2]}"]
- return template
- end
- if template_format == :js && template = self.view_paths["#{template_file_name}.html#{lang}"]
- @template_format = :html
- return template
- end
- nil
- end
- memoize :_pick_template_sub
-
- unmemoize :_pick_template if memoized? :_pick_template
- def _pick_template(template_path)
- return template_path if template_path.respond_to?(:render)
-
- path = template_path.sub(/^\//, '')
- if ( m = path.match(/(.*)\.(\w+)$/) ) &&
- ActionView::Template.template_handler_extensions.include?(m[2])
- template_file_name, template_file_extension = m[1], m[2]
- else
- template_file_name = path
- end
-
- # search for localized version
- if controller && controller.respond_to?(:request)
- controller.request.accepts_languages.each do |lang|
- if template = _pick_template_sub(template_file_name, ".#{lang}")
- controller.request.language= lang
- return template
- end
- end
- end
-
- # search for not localized version
- if template = _pick_template_sub(template_file_name)
- template
- else
- # not found in view_paths
- template = ActionView::Template.new(template_path, view_paths)
-
- if self.class.warn_cache_misses && logger
- logger.debug "[PERFORMANCE] Rendering a template that was " +
- "not found in view path. Templates outside the view path are " +
- "not cached and result in expensive disk operations. Move this " +
- "file into #{view_paths.join(':')} or add the folder to your " +
- "view path list"
- end
-
- template
- end
- end
-
- end
-
- #### for correct mime-type detection
-
- module ActionView
- class Template
- attr_accessor :language
-
- def initialize(template_path, load_paths = [])
- template_path = template_path.dup
- @base_path, @name, @format, @language, @extension = split(template_path)
- @base_path.to_s.gsub!(/\/$/, '') # Push to split method
- @load_path, @filename = find_full_path(template_path, load_paths)
-
- # Extend with partial super powers
- extend RenderablePartial if @name =~ /^_/
- end
-
- unmemoize :format_and_extension
- def format_and_extension
- (extensions = [format, language, extension].compact.join(".")).blank? ? nil : extensions
- end
- memoize :format_and_extension
-
- unmemoize :path
- def path
- [base_path, [name, format, language, extension].compact.join('.')].compact.join('/')
- end
- memoize :path
-
- unmemoize :path_without_extension
- def path_without_extension
- [base_path, [name, format, language].compact.join('.')].compact.join('/')
- end
- memoize :path_without_extension
-
- unmemoize :path_without_format_and_extension
- def path_without_format_and_extension
- [base_path, name].compact.join('/')
- end
- memoize :path_without_format_and_extension
-
- private
-
- # Returns file split into an array
- # [base_path, name, format, language, extension]
- def split(file)
- if m = file.match(/^(.*\/)?([^\.]+)(?:\.(\w+)(?:\.(\w+)(?:\.(\w+)(?:\.(\w+))?)?)?)?$/)
- if m[6] # multi part format
- [m[1], m[2], "#{m[3]}.#{m[4]}", m[5], m[6]]
- elsif m[5]
- if ActionController::AbstractRequest.acceptable_language?(m[4])
- [m[1], m[2], m[3], m[4], m[5]]
- else # multi part format
- [m[1], m[2], "#{m[3]}.#{m[4]}", m[5]]
- end
- elsif m[4] # no format
- if valid_extension?(m[4])
- if ActionController::AbstractRequest.acceptable_language?(m[3])
- [m[1], m[2], nil, m[3], m[4]]
- else # Single format
- [m[1], m[2], m[3], nil, m[4]]
- end
- else
- [m[1], m[2], m[3], m[4], nil]
- end
- else
- if valid_extension?(m[3])
- [m[1], m[2], nil, nil, m[3]]
- elsif ActionController::AbstractRequest.acceptable_language?(m[3])
- [m[1], m[2], nil, m[3], nil]
- else
- [m[1], m[2], m[3], nil, nil]
- end
- end
- end
- end
- end
- end
-
- #### for page cache
-
- module ActionController::Caching::Pages
- def cache_page(content = nil, options = nil)
- return unless perform_caching && caching_allowed
-
- path = case options
- when Hash
- url_for(options.merge(
- :only_path => true,
- :skip_relative_url_root => true,
- :format => params[:format],
- :rails_language => request.accepts_languages.first))
- when String
- options
- else
- p= request.path.split('.')
- p.pop if ActionController::AbstractRequest.acceptable_language?(p.last)
- p[0]+= self.class.page_cache_extension if p.count==1
- p << request.accepts_languages.first
- p.join('.')
- end
-
- self.class.cache_page(content || response.body, path)
- end
- end
-
- #### for action cache
-
- module ActionController::Caching::Actions
- class ActionCachePath
- attr_reader :language
-
- def initialize(controller, options = {}, infer_extension=true)
- if infer_extension and options.is_a? Hash
- request_extension = extract_extension(controller.request)
- options = controller.params.merge(
- options.reverse_merge(
- :format => request_extension,
- :rails_language => controller.request.accepts_languages.first))
- end
- path = controller.url_for(options).split('://').last
- if infer_extension
- @extension = request_extension
- add_extension!(path, @extension)
- end
- @path = URI.unescape(path)
- end
-
- private
-
- def add_extension!(path, extension)
- if extension
- p= path.split('.')
- p.insert(-2, extension) unless path =~ /\b#{Regexp.escape(extension)}\b/
- p.join('.')
- end
- end
-
- def extract_extension(request)
- p= request.path.split('.')
- # drop file name
- p.shift
- # drop language
- p.pop if !p.empty? && ActionController::AbstractRequest.acceptable_language?(p.last)
- extension = p.join('.')
-
- # If there's no extension in the path, check request.format
- extension = request.cache_format if extension==""
-
- extension
- end
- end
- end
-
- #### for fragment cache
-
- module ActionController
- module Caching
- module Fragments
- def fragment_cache_key(key)
- ActiveSupport::Cache.expand_cache_key(
- key.is_a?(Hash) ?
- url_for(key.reverse_merge(
- :rails_language=>request.accepts_languages.first)
- ).split("://").last :
- key,
- :views)
- end
- end
- end
- end
-
* プラグイン化 [#j4d21556]
http://akimichi.homeunix.net/hiki/rails/?%A5%D7%A5%E9%A5%B0%A5%A4%A5%F3 ~
@@ -1864,6 +1465,7 @@
動作チェック
+ LANG:console
$ wgetc http://localhost/negotiation/test
English: Test OK
@@ -1885,7 +1487,7 @@
残るはドキュメントとテストケースだ。
-* テスト [#z90f29b8]
+* テストケース [#z90f29b8]
プラグインのテストケースを書かなければ。
@@ -1894,52 +1496,574 @@
言語に依存しないテンプレートがある場合にどうなるか、
ちゃんと試してみる必要がありそう。
-とりあえずここまで、残りは後で。
+** テストの動かし方 [#u8d040b6]
-http://blog.omdb-beta.org/ のコードを覚え書き。
+まずいきなりテストしてみる。
+ LANG:console
+ $ cd vendor/plugins/lanugage_negotiation/
+ $ rake
+ (in (rails)/negotiation/vendor/plugins/lanugage_negotiation)
+ /usr/bin/ruby1.8 -I"(rails)/negotiation/vendor/plugins/lanugage_negotiation/lib" \
+ -I"(rails)/negotiation/vendor/plugins/lanugage_negotiation/lib" \
+ -I"(rails)/negotiation/vendor/plugins/lanugage_negotiation/test" \
+ "/usr/lib/ruby/1.8/rake/rake_test_loader.rb" "test/lanugage_negotiation_test.rb"
+ /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- active_support (LoadError)
+ from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'
+ from (rails)/negotiation/vendor/plugins/lanugage_negotiation/test/test_helper.rb:2
+ from ./test/lanugage_negotiation_test.rb:1:in `require'
+ from ./test/lanugage_negotiation_test.rb:1
+ from /usr/lib/ruby/1.8/rake/rake_test_loader.rb:5:in `load'
+ from /usr/lib/ruby/1.8/rake/rake_test_loader.rb:5
+ from /usr/lib/ruby/1.8/rake/rake_test_loader.rb:5:in `each'
+ from /usr/lib/ruby/1.8/rake/rake_test_loader.rb:5
+ rake aborted!
+ Command failed with status (1): [/usr/bin/ruby1.8 -I"(rails)/...]
+
+ (See full trace by running task with --trace)
+ $ cat test/test_helper.rb
+ require 'rubygems'
+ require 'active_support'
+ require 'active_support/test_case'
+
+パスが通っていないらしい。
+
+確かに通ってないんだけど、いくら何でも通ってなさすぎ。~
+どうしてこんな事に?
+
+ああ、この rake をいきなり起動しちゃだめなのね。
+
+アプリケーションのホームから、
+
+ LANG:console
+ $ cd ../../..
+ $ pwd
+ (rails)/negotiation
+ $ rake test:plugins
+ (in (rails)/negotiation)
+ /usr/bin/ruby1.8 -I"(rails)/negotiation/lib" -I"(rails)/negotiation/test" \
+ "/usr/lib/ruby/1.8/rake/rake_test_loader.rb" "vendor/plugins/lanugage_negotiation/test/lanugage_negotiation_test.rb"
+ Loaded suite /usr/lib/ruby/1.8/rake/rake_test_loader
+ Started
+ .
+ Finished in 0.035457 seconds.
+
+ 1 tests, 1 assertions, 0 failures, 0 errors
+
+うまく行ってる。
+
+** プラグインのテストの作成 [#n11b0fa7]
+
+あとは vendor/plugins/lanugage_negotiation/test/lanugage_negotiation_test.rb に
+テストケースをもりもり書いていけばいい。
+
+テストの書き方は~
LANG:ruby(linenumber)
- def test_caching_show
- accept :xml
- # language is a custom extension
- language :de
- page = "/casts/#{casts(:first).id}.xml.de"
- assert_cached_page( page ) do
- get :show, :id => casts(:first).id
- assert_response :success
- end
+ test "what to test" do
+ assert true
+ assert_equal 1, 1
end
+
+という感じ。
+
+詳しい書式: http://www.ruby-lang.org/ja/man/html/Test_Unit.html
+
+ LANG:ruby(linenumber)
+ test "ActionController_AbstractRequest_acceptable_language?" do
- def test_expire_show
- accept :xml
- language :de
- page = "/casts/#{casts(:first).id}.xml.de"
- assert_no_cached_page( page ) do
- put :update, :id => casts(:first).id,
- :job => Job.composer.id
- assert_response :success
- end
- end
+ ar = ActionController::AbstractRequest
+ ar.class_eval <<-EOS
+ def self.acceptable_languages=(v)
+ @acceptable_languages = v
+ end
+ EOS
- def test_expire_fragment
- accept :js
- language :en
- params = { :controller => 'casts',
- :id => casts(:first).id,
- :template => 'cast' }
- assert_cached_fragment( params ) do
- put :update, :id => casts(:first).id,
- :job => Job.composer.id
- assert_template 'cast'
+ ar.acceptable_languages= :ja, :en, :fr
+
+ assert ar.acceptable_language? :ja
+ assert ar.acceptable_language? :en
+ assert ar.acceptable_language? :fr
+
+ assert ! ar.acceptable_language?(:de)
+ assert ! ar.acceptable_language?(:es)
+
+ assert ar.acceptable_language? "fr"
+ assert ! ar.acceptable_language?("de")
+ end
+
+問題なし。
+
+ LANG:ruby(linenumber)
+ test "ActionController_AbstractRequest_accepts_languages!" do
+
+ ar= ActionController::AbstractRequest
+ ar.class_eval <<-EOS
+ def self.acceptable_languages=(v)
+ @acceptable_languages = v
+ end
+ attr :cookies, true
+ attr :env, true
+ EOS
+
+ rec = ar.new
+ ar.acceptable_languages= :ja, :en, :fr
+ rec.cookies = {}
+ rec.env = {}
+
+ # server default
+ assert_equal [ :ja, :en, :fr ], rec.accepts_languages!
+
+ # ignore invalid specifications
+ rec.cookies = { 'rails_language' => ['xx'] }
+ rec.env = { 'HTTP_ACCEPT_LANGUAGE' => 'es, de' }
+ assert_equal [ :ja, :en, :fr ], rec.accepts_languages!
+
+ # Accept-Language
+ rec.env = { 'HTTP_ACCEPT_LANGUAGE' => 'en-us, fr, en, ja' }
+ assert_equal [ :en, :fr, :ja ], rec.accepts_languages!
+
+ rec.env = { 'HTTP_ACCEPT_LANGUAGE' => 'en-us;q=0.8, fr;q=0.1, en, ja' }
+ assert_equal [ :en, :fr, :ja ], rec.accepts_languages!
+
+ # cookie
+ rec.cookies = { 'rails_language' => ['ja'] }
+ assert_equal [ :ja, :en, :fr ], rec.accepts_languages!
+
+ rec.cookies = { 'rails_language' => ['fr'] }
+ assert_equal [ :fr, :en, :ja ], rec.accepts_languages!
+
+ rec.env = {}
+ assert_equal [ :fr, :ja, :en ], rec.accepts_languages!
+
+ # arg
+ assert_equal [ :ja, :fr, :en ], rec.accepts_languages!('ja')
+
+ assert_equal [ :en, :fr, :ja ], rec.accepts_languages!('en')
+
+ assert_equal [ :fr, :ja, :en ], rec.accepts_languages!('fr')
+
+ end
+
+テストに引っかかった。
+
+ LANG:ruby
+ class ActionController::AbstractRequest.accepts_languages!(language=nil)
+ ...
+
+ lsym= l.split(/;|\-/,2)[0].downcase.to_sym
+
+の部分、
+
+ LANG:ruby
+ lsym= l.split(/;|\-/,2)[0].strip.downcase.to_sym
+
+とする必要有り。
+
+ LANG:ruby(linenumber)
+ class MemoizedTestClass
+ extend ActiveSupport::Memoizable
+ def count
+ @count
+ end
+ def calc(v)
+ @count= ( @count || 0 ) + 1
+ v
+ end
+ memoize :calc
+ end
+
+ test "memoize" do
+ mt= MemoizedTestClass.new
+ mt.calc(1)
+ mt.calc(2)
+ mt.calc(1)
+ mt.calc(3)
+ mt.calc(1)
+ assert_equal 3, mt.count
+ mt.calc(1)
+ mt.calc(2)
+ mt.calc(3)
+ assert_equal 3, mt.count
+ mt.calc(4)
+ assert_equal 4, mt.count
+ assert MemoizedTestClass.memoized?(:calc)
+ MemoizedTestClass.unmemoize :calc
+ assert !MemoizedTestClass.memoized?(:calc)
+ assert_equal 4, mt.count
+ mt.calc(1)
+ mt.calc(2)
+ mt.calc(3)
+ mt.calc(4)
+ assert_equal 8, mt.count
+ MemoizedTestClass.memoize :calc
+ mt.calc(1)
+ mt.calc(2)
+ mt.calc(3)
+ assert_equal 8, mt.count
+ end
+
+unmemoize 後にもう一度 memoize した場合には、
+以前の計算結果が残ってしまうことに注意。
+
+ LANG:ruby(linenumber)
+ module ActiveSupport::Memoizable
+ def unmemoize(*symbols)
+ class_eval <<-EOS, __FILE__, __LINE__
+ #{memoized_ivar}= nil
+
+などと書いてたけれど、呼び出されるコンテキストが
+異なるので変数のクリアはできない。
+
+この行は削除した。
+
+ LANG:console
+ $ rake test:plugins
+ /usr/bin/ruby1.8 -I"(rails)/negotiation/lib" -I"(rails)/negotiation/test" "/usr/lib/ruby/1.8/rake/rake_test_loader.rb" "vendor/plugins/lanugage_negotiation/test/lanugage_negotiation_test.rb"
+ Loaded suite /usr/lib/ruby/1.8/rake/rake_test_loader
+ Started
+ ...
+ Finished in 0.038165 seconds.
+
+ 3 tests, 25 assertions, 0 failures, 0 errors
+
+テスト成功。
+
+他にももう少し plugin test でちまちま書いてく事もできるんだけど、
+controller の test と合わせていっきにやってしまった方が楽そう?
+
+** negotiation アプリケーションのテストケース [#p80291d3]
+
+コントローラ込みのファンクショナルテストについては、
+プラグインのテストケースに入れるわけに行かないので、
+negotiation アプリケーションの
+test コントローラのテストケースとして書く事になる。
+
+まずテストに必要なアクションとビューを追加。
+
+ LANG:console
+ $ jed app/controllers/test_controller.rb
+ class TestController < ApplicationController
+ caches_page :pagecached
+ caches_action :actioncached
+ def index
+ end
+ def pagecached
+ end
+ def actioncached
+ end
+ def fragmentcached
+ end
+ def render_action
+ render :action => :acceptid
+ end
+ def render_file
+ render :file => "test/acceptid.html"
+ end
+ def acceptid
+ end
+ end
+ $ echo "Test <%= render :partial=>'ok' %>" > app/views/test/index.html.en.erb
+ $ echo "テスト <%= render :partial=>'ok' %>" > app/views/test/index.html.ja.erb
+ $ echo "Page cached" > app/views/test/pagecached.html.en.erb
+ $ echo "ページキャッシュ" > app/views/test/pagecached.html.ja.erb
+ $ echo "Action cached" > app/views/test/actioncached.html.en.erb
+ $ echo "アクションキャッシュ" > app/views/test/actioncached.html.ja.erb
+ $ echo "<% cache :param1=>:test do %>Fragment cached <%= render :partial=>'ok' %><% end %>" > app/views/test/fragmentcached.html.en.erb
+ $ echo "<% cache do %>フラグメントキャッシュ <%= render :partial=>'ok' %><% end %>" > app/views/test/fragmentcached.html.ja.erb
+ $ echo "File" > app/views/test/renderfile_.html.en.erb
+ $ echo "ファイル" > app/views/test/renderfile_.html.ja.erb
+ $ echo "html <%= params[:id] %>" > app/views/test/acceptid.html.ja.erb
+ $ echo "text <%= params[:id] %>" > app/views/test/acceptid.text.ja.erb
+ $ echo "English <%= @content_for_layout %>" > app/views/layouts/application.text.en.erb
+
+テストは test/functional/test_controller_test.rb に書き込む。
+
+書き方は http://d.hatena.ne.jp/elm200/20070724/1185282738 が参考になる。
+
+ LANG:ruby(linenumber)
+ def setup
+ @ar = ActionController::AbstractRequest
+ @controller = TestController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+としておくと、
+
+ LANG:ruby(linenumber)
+ test "server default1" do
+ @ar.acceptable_languages = :ja, :en, :fr
+ @request.cookies = {}
+ @request.env = {}
+ get :index, :format=>"html"
+ assert_response :success
+ assert_template 'index.html.ja'
+ assert_equal "/test", @request.request_uri
+ end
+
+のようなコードを書く事ができる。
+
+キャッシュをテストするために、~
+config/environments/test.rb
+ LANG:ruby(linenumber)
+ config.action_controller.perform_caching = true
+
+さらに、
+ LANG:ruby(linenumber)
+ def assert_cached_page_exists( page )
+ full_path= ActionController::Base.__send__(:page_cache_path, page)
+ assert File.exist?(full_path), "Cached file '#{full_path}' not created."
+ end
+
+ def assert_cached_page( page )
+ ActionController::Base.class_eval <<-EOS
+ @@page_cache_directory = defined?(Rails.public_path) ? Rails.public_path : ""
+ @@page_cache_directory += "/cahce_in_test_environment"
+ EOS
+ @controller.expire_page page
+ yield
+ assert_cached_page_exists page
+ end
+
+として、development や production 環境にキャッシュを作成してしまわないようにする。
+
+ LANG:ruby(linenumber)
+ test "page cache 1" do
+ @ar.acceptable_languages = :fr, :ja, :en
+ @request.cookies = {}
+ @request.env = { }
+ page = "/test/pagecached.html.fr"
+ assert_cached_page( page ) do
+ get :pagecached, :format=>"html"
+ assert_response :success
+ assert_template 'pagecached.html.ja'
+ assert_equal "/test/pagecached", @request.request_uri
+ assert_layout "layouts/application.html.ja"
+ end
+ end
+
+のようにテストする事ができる。
+
+その他作ったヘルパー関数達
+
+ LANG:ruby(linenumber)
+ def assert_content_type(type)
+ flunk "Content-Type '#{type}' was expected but "+
+ "'#{@response.content_type}' found." unless
+ @response.content_type == type
+ end
+
+ def assert_cached_fragment_exists(key, message="Fragment cache ['#{key}'] not exists.")
+ flunk message unless @controller.fragment_exist? key
+ end
+
+ def assert_cached_fragment(key)
+ @controller.expire_fragment key
+ yield
+ assert_cached_fragment_exists key
+ end
+
+ def assert_layout(v)
+ assert_equal v, @response.template.send(
+ :_pick_template, @response.layout).path_without_extension
+ end
+
+ def log(s)
+ if s.is_a? String
+ Rails.logger.warn s
+ else
+ Rails.logger.warn s.inspect
+ end
+ end
+
+テストはかなりたくさん書いたので、ここに全部は載せない。~
+一部を取り出すと、
+
+ LANG:ruby(linenumber)
+ test "page cache 3" do
+ @ar.acceptable_languages = :fr, :ja, :en
+ @request.cookies = {}
+ @request.env = { 'HTTP_ACCEPT_LANGUAGE' => 'xx' }
+ page = "/test/pagecached.html.fr"
+ assert_cached_page( page ) do
+ get :pagecached, :format=>"html"
+ assert_response :success
+ assert_template 'pagecached.html.ja'
+ assert_equal "/test/pagecached", @request.request_uri
+ assert_layout "layouts/application.html.ja"
+ assert_content_type "text/html"
+ end
+ end
+
+ test "page cache 4" do
+ @ar.acceptable_languages = :fr, :ja, :en
+ @request.cookies = {}
+ @request.env = { 'HTTP_ACCEPT_LANGUAGE' => 'en' }
+ page = "/test/pagecached.html.en"
+ assert_cached_page( page ) do
+ get :pagecached, :format=>"html", :extra=>:param
+ assert_response :success
+ assert_template 'pagecached.html.en'
+ assert_equal "/test/pagecached?extra=param", @request.request_uri
+ assert_layout "layouts/application.html.en"
+ assert_content_type "text/html"
+ end
+ end
+
+ test "action cache 1" do
+ @ar.acceptable_languages = :fr, :ja, :en
+ @request.cookies = {}
+ key = "test.host/test/actioncached?rails_language=fr"
+ assert_cached_fragment( key ) do
+ get :actioncached, :format=>"html"
+ assert_response :success
+ assert_template 'actioncached.html.ja'
+ assert_equal "/test/actioncached", @request.request_uri
+ assert_layout "layouts/application.html.ja"
+ assert_content_type "text/html"
+ end
+ end
+
+ test "action cache 2" do
+ @ar.acceptable_languages = :fr, :ja, :en
+ @request.cookies = {}
+ key = "test.host/test/actioncached.ja"
+ assert_cached_fragment( key ) do
+ get :actioncached, :format=>"html", :rails_language=>"ja"
+ assert_response :success
+ assert_template 'actioncached.html.ja'
+ assert_equal "/test/actioncached.ja", @request.request_uri
+ assert_layout "layouts/application.html.ja"
+ assert_content_type "text/html"
+ end
+ end
+
+こんな感じ。
+
+実際にこれを走らせる。
+
+ LANG:console
+ $ rake test:functionals
+ rake aborted!
+ no such file to load -- (rails)/negotiation/db/schema.rb
+
+ (See full trace by running task with --trace)
+ $ rake db:schema:dump
+ $ rake test:functionals
+ /usr/bin/ruby1.8 -I"(rails)/negotiation/lib" -I"(rails)/negotiation/test" "/usr/lib/ruby/1.8/rake/rake_test_loader.rb" "test/functional/test_controller_test.rb"
+ Loaded suite /usr/lib/ruby/1.8/rake/rake_test_loader
+ Started
+ ..........................
+ Finished in 0.358801 seconds.
+
+ 26 tests, 96 assertions, 0 failures, 0 errors
+
+実行は rake test:functionals で良い。~
+schema.rb が無いと言われたので、rake db:schema:dump で作成した。
+
+ミスして入力したテストで気づいた点。
+
+ LANG:ruby(linenumber)
+ module ActionView
+ class Template
+ def split(file)
+ elsif ActionController::AbstractRequest.acceptable_language?(m[3])
+
+の部分などで、m[3] が nil になった場合、
+
+ LANG:ruby(linenumber)
+ class ActionController::AbstractRequest
+ def self.acceptable_language?(l)
+ acceptable_languages.include?(l.to_sym)
end
- assert_no_cached_fragment( params ) do
- casts(:first).save
- end
end
+の l.to_sym でこける。
+ LANG:ruby(linenumber)
+ def self.acceptable_language?(l)
+ l.respond_to?(:to_sym) && acceptable_languages.include?(l.to_sym)
+ end
+
+とすべき。
+
+また、routes.rb では
+ LANG:ruby(linenumber)
+ map.connect ':controller/:action/:id', :format => 'html'
+
+を始めの方に書いておかないと、
+ LANG:ruby(linenumber)
+ url_for(:controller=>:test, :action=>:acceptid, :index=>1, :format=>"html")
+
+が
+ LANG:ruby(linenumber)
+ map.connect ':controller/:action/:id.:rails_language', :format => 'html',
+ :requirements => { :rails_language => lang_regexp }
+
+を使って変換されてしまい、
+ /test/acceptid/1.
+
+となるので、順番を入れ替える。
+
+* fcgi 化 [#wd595311]
+
+ちょっとオフトピックだけれど、はまったので。
+
+fcgi 化するには基本的には RewriteRule で dispatch.cgi となっていたところを
+dispatch.fcgi にするだけでよい。
+
+ LANG:console
+ $ jed public/.htaccess
+ RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
+ $ wgetc --header="Accept-Language: en" http://localhost/negotiation/test
+ エラー: ActionController::RoutingError (no route found to match to "/negotiation/test")
+
+でも、なんでかうまくいかない。~
+.htaccess の SetEnv RAILS_RELATIVE_URL_ROOT /negotiation の効果が得られていないみたい。
+
+ vendor/actionpack/CHANGELOG
+ *2.2 (November 21st, 2008)*
+ * AbstractRequest.relative_url_root is no longer automatically configured
+ by a HTTP header. It can now be set in your configuration environment with
+ config.action_controller.relative_url_root [Josh Peek]
+
+どうやらこれらしい。~
+なんで fcgi の時だけだめなんだろう?
+
+changelog に書かれているのだからバグという事でもないのだろうし、
+コードを追うのはやめにして、素直に environments/production.rb に
+設定を追加したところ、動き出した。
+
+さすが、cgi に比べると段違いに速い。
+
+ LANG:console
+ $ echo 'config.action_controller.relative_url_root = "/negotiation"' >> environments/production.rb
+ $ wgetc --header="Accept-Language: en" http://localhost/negotiation/test
+ 日本語: テスト ばっちり
+ $ rm tmp/wget.cookie
+ $ wgetc --header="Accept-Language: en" http://localhost/negotiation/test
+ English: Test OK
+ $ wgetc --header="Accept-Language: en" http://localhost/negotiation/test.ja
+ 日本語: テスト ばっちり
+ $ wgetc --header="Accept-Language: en" http://localhost/negotiation/test
+ 日本語: テスト ばっちり
+ $ wgetc http://localhost/negotiation/test/pagecached
+ 日本語: ページキャッシュ
+ $ ls public/test/*
+ public/test/pagecached.html.ja
+ $ wgetc http://localhost/negotiation/test/pagecached.en
+ English: Page cached
+ $ ls public/test/*
+ public/test/pagecached.html.en public/test/pagecached.html.ja
+
+* プラグインとしての体裁を整える [#a85568da]
+
+git に入れる?
+
+tar ball でいい?
+
* コメント [#kfcbe2ab]
-気づいた点など、ぜひとも突っ込みを入れて下さい。
+気づいた点など、ぜひ突っ込みを入れて下さい。
#article_kcaptcha