- yumで依存するパッケージをインストールする(全部いるのかどうかは分からない)
- “Here is a variant with rbenv.”の方に従って、
- rbenvをインストール
- ruby-buildをインストール
- /etc/profile.d/rbenv.shファイルを作成
- “. /etc/profile”を実行
- Rubyをインストール(必要に応じてバージョンを指定する)
僕らはプールの底を歩き続ける。まるで自分の影とダンスを踊るように。
CentOSにRedmine 1.4 + Passenger(mod_rails)をセットアップする際に参考にしたリンク集のメモ。
Webで公開されている、プログラム言語・フレームワーク・DBのマニュアル(リファレンス)サイトへのリンクをまとめてみた。
選んだ基準は、できるだけ日本語で、なるべく分かりやすいこと。それを満たすなら公式リファレンスより非公式のものを優先している。
Rails2.3で試した。
必要最低限の要素のみ。
config/routes.rb
map.connect "sitemap.xml", :controller => :test, :action => :sitemap
class TestController < ApplicationController
def sitemap
# サイトマップとして送信したいページのURL生成に必要な情報を取得する
@members = Member.find(:all)
@entries = Entry.find(:all)
headers["Content-Type"] = "text/xml; charset=utf-8"
respond_to do |format|
format.xml {render :layout => false}
end
end
end
xml.instruct!「http://」から始まるフルなURLにするために「:only_path => false」を付けている。
xml.urlset(:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9") do
# トップページ
xml.url do
xml.loc(url_for(:controller => :top, :only_path => false))
end
# 個別のページ
@members.each do |member|
xml.url do
xml.loc(url_for(:controller => :members, :action => :show, :id => member.id, :only_path => false))
end
end
・
・
・
end
# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file
#
# To ban all spiders from the entire site uncomment the next two lines:
# User-Agent: *
# Disallow: /
Sitemap: http://www.example.com/sitemap.xml
RailsでActiveRecordのValidationによって生成されるエラーメッセージを翻訳するためのメモ。
方法その1:I18nを使う
所定のYAMLに翻訳部分を記述しておく方法。現在はこれが一番スマートなようだ。
(フィールド名とその後のメッセージの間に半角スペースが入ってしまう?)
参考:
Rails 2.2.2でエラーメッセージを日本語化する。|WEBデザイン Tips
Rails 2.2 の ActiveRecord::Validations#add のソースコードを読む - Ruby on Rails 研究 - Ruby on Rails with OIAX
方法その2:GetTextを使う
ActiveRecord::Errorsのdefault_error_messagesをゴリゴリ書き換える方法。
例えば、基本となるModelを作ってその中でメッセージをセットし、他のモデルはそれを継承する方法でもよいと思う。
class BaseModel < ActiveRecord::Baseただし最新のRailsではDeprecation::warnの対象?
ActiveRecord::Errors.default_error_messages[:invalid] = _("がおかしいよ!")
ActiveRecord::Errors.default_error_messages[:empty] = _("を入力してね!")
・
・
end
tags: active-record, gettext, i18n, rails, ruby, validation 0 コメント
RailsのViewで部分テンプレートであるpartialを呼び出す場合、呼び出し時に :object または :collection と :locals を渡すことができる。
<%= render :partial => "msg", :object => "データ", :locals => {:name => "他のデータ"} %>
<%= render :partial => "msg", :collection => ["データ1", "データ2"] %>
#_msg.html.erb
<%= msg %> <= ここにデータが入っている
<%= name %> <= :localsで渡したデータは指定した名前の変数に入っている。
いくつかプラグインがあるが、acts_as_taggable_on_steroidsが一番人気のようだ。
acts_as_taggable_on_steroidsの使い方は、acts_as_taggable_on_steroidsの使い方まとめ - ひげろぐが参考になる。
acts_as_taggable_on_steroidsのインストール元については、Railsのtagプラグイン「acts_as_taggable_on_steroids」がgithubに行ってた - 常識という迷信にあるとおり、現在はgithubにあるのが最新のようだ。
上記の参考サイトではacts_as_taggable_on_steroidsの機能をフルに使っているが、タグクラウドを表示したいだけなら下記だけでOK。
# tag_sample.rb
class TagSample
attr_accessor :count, :label
end
# FooController.rb
# 実際にはDBから取得したデータとかをループで処理するだろうけど
tag1 = TagSample.new
tag1.count = 10
tag1.label = "ラベル1"
tag2 = TagSample.new
tag2.count = 20
tag2.label = "ラベル2"
@tags = [tag1, tag2]
# foo_helper.rb
module FooHelper
include TagsHelper
end
<!-- foo/bar.html.erb -->
<% tag_cloud(@tags, ["tag-s", "tag-m", "tag-l"]) do |tag, css| %>
<%= link_to(h(tag.label), {:action=> :tags, :id => tag.label}, :class => css) %>
<% end %>
a.tag-s { font-size: 80%; }
a.tag-l { font-size: 150%; }
Railsで特定のページだけにCSSファイルを追加する方法を見て知った。これは便利。
application.html.erb等で、 yieldにパラメータを指定すればOK。
<html>
<head>
<title>テスト</title>
<%= yield :head %>
</head>
<body>
<%= yield %>
<%= yield :foot %>
</body>
</html>
<h1>head and foot</h1>
<% content_for :head do %>
<%= stylesheet_link_tag "foo" %>
<% end %>
<% content_for :foot do %>
<%= javascript_include_tag "bar" %>
<% end %>
<html>
<head>
<title>テスト</title>
<link href="/stylesheets/foo.css?1345990170" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>head and foot</h1>
<script src="/javascripts/bar.js?1350833305" type="text/javascript"></script>
</body>
</html>
tags: css, javascript, rails, ruby 0 コメント
Rails2.3で日付選択ヘルパー(select_date)を使うためのメモ。
オプションとして指定できるものはこんな感じのようだ。
<%
options = {
:prefix => 'payday', # field名のprefix
:order => [:month, :year, :day], # 表示順
:date_separator => '/', # 項目間の区切り
:prompt => true, # 選択リストの一番上の表示について。個別の指定も可
:include_blank => true, # 選択リストの一番上のブランクにする
:use_month_numbers => true, # 月を数字で表す
# 選択可能な年の範囲を指定
:start_year => Date.today.year,
:end_year => Date.today.year + 1,
# 非表示にする
:discard_year => true,
:discard_month => true,
:discard_day => true
}
html_options = {} # ?
%>
<%= select_date(Date.today + 2.days, options, html_options) %>
AtcitveFormはテーブルに紐付かないモデルを使って入力フォームを作るためのプラグイン。
データの入れ物とvalidationを担う。
「ActiveForm」という名前のプラグインは複数あるので注意。
Gemでインストールすると、module版のActiveFormがインストールされるが、よく分からなかったのでパス。
どうやら「RealityForge」で公開されたActiveFormが主流のようだ。
最新版?:
maciej's active_form at master - GitHub
使い方:
RailsのActiveFormの使い方 - 京の路
Ruby on Rails プラグイン まとめ wiki - active_formプラグイン
るびすけの開発日記 ~Ruby on Rails~ - IT業界のための転職サイト -
Rails2.2以降ではエラーが発生する。
undefined method `self_and_descendants_from_active_record' for Xxx:Class
#コントローラ
class SearchController < ApplicationController
def index
@search = Search.new(params[:search])
if params[:search]
@search.valid?
end
end
end
#モデル
require 'active_form'
class Search < ActiveForm
attr_accessor :tag
validates_presence_of :tag
validates_length_of :tag, :maximum => 3
def validate
# カスタム入力チェックはここで
end
end
<!-- ビュー -->
<% form_for(:search, @search) do |f| %>
<%= error_messages_for :search, "tag" %>
<%= f.text_field "tag" %>
<% end %>
レアなケースだろうけど一応メモ。
(参考:RailsでGetText)
Rails のためのものぐさな Web アプリケーションの国際化手法 - 川o・-・)<2nd lifeが参考になる。
ただしGetText 2.0からはenvironment.rbで読み込むgemが変わったので注意。
config.gem "locale_rails"
config.gem "gettext_activerecord"
config.gem "gettext_rails"
config.frameworks -= [ :active_record, :action_mailer ]
localeActiveRecordは使わないのでgettext_activerecordは入れなかった。
locale_rails
gettext
gettext_rails
ruby server/script
↓
.../lib/active_support/core_ext/module/aliasing.rb:33:in `alias_method': undefined method `create!' for class `ActionMailer::Base' (NameError)
config.frameworks -= [ :active_record, :action_mailer ]
↓
config.frameworks -= [ :active_record ]
参照系しか試してない。
下記の例では、MemberというActiveResourceをリスト表示したり詳細表示したりするControllerについて、RSpecでテストする。
(参考:ActiveResource の使い方(前編) : Rails 同士で通信する - WebOS Goodies ※「ユニットテスト」の項。RSpecではないけど。)
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
require 'active_resource/http_mock'
describe MembersController do
before do
@member = {:id => 1, :name => 'foo'}
@members = [@member]
@header = Member.connection.__send__(:build_request_headers, {}, :get)
ActiveResource::HttpMock.respond_to do |mock|
mock.get '/members.xml', @header, @members.to_xml(:root => 'members')
mock.get '/members/1.xml', @header, @member.to_xml(:root => 'member')
end
end
#後は普通にケースを書く
#(略)
end
mock.get '/members.xml?q=keyword', @header, @members.to_xml(:root => 'members')
before doActiveResourceでもActiveRecordでもModelであることには違いがないから、ただMockを使えば良いだけだった。
@member = mock_model(Member)
Member.should_receive(:find).with(:all).and_return(@member)
get 'index'
end
RSpecはDSLなので、決め事を覚えないと使いこなせない。
よく使うことになるであろう、参考リンクを列挙しておく。
前処理、後処理
#例
response.should render_template('members/index')
#例
member = mock_model(Member)
member.stub!(:id).and_return(100)
member.id.should == 100 # => これはOK(Green)だが...
#Viewで「link_to('link', member)」している部分をテスト
response.should have_tag('a[href=?]', '/members/100') # => これはNG(Red)になる
#調べてみると、内部的なIDが使われたようで、「/members/1001」というパスになっていた
member = mock_model(Member, :id => 100)
やったことのメモ。
インストール
gemでRSpecをインストール(もしかして不要?)
gem install rspec
gem install rspec-rails(rspec_railsだと見つからない)
ruby script/generate rspec
ruby script/generate rspec_model Member
ruby script/spec spec/models/member_spec.rbまたは
rake spec:modelsなどなど。(参考:RSpec on Rails でインストールされる rake タスク)
.../spec/spec_helper.rb:16: undefined method `use_transactional_fixtures=' for #<Spec::Runner::Configuration:0x1234567> (NoMethodError)上記のソース(spec/spec_helper.rb)にはこう書いてある。
# If you're not using ActiveRecord you should remove these書いてあるとおり、この3行を削除したら無事動いた。
# lines, delete config/database.yml and disable :active_record
# in your config/boot.rb
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = false
config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
基本:
ActiveResourceでいろんなAPIを叩いてみる。標的はHotpepper API - 富士山は世界遺産
発行されるURLと拡張子について:
天使やカイザーと呼ばれて: ActiveResourceで拡張子なしのURIを発行する方法
応用編:
ActiveResource の使い方(前編) : Rails 同士で通信する - WebOS Goodies
ActiveResource の使い方(中編) : メソッドの詳細 - WebOS Goodies
(後編は? 2009/09/17追記:公開された↓)
ActiveResource の使い方(後編) : 一般の Web API にアクセスする - WebOS Goodies
ActiveResourceのバグ?
[PATCH] ActiveResource find(:all) method returns "NoMethodError: undefined method `collect!'... - lambda {|diary| lambda { diary.succ! } }.call(hatena)
取得するXMLがn件のデータを包含する要素を持つ形の場合、包含する要素に属性type="array"が無いと「collect!メソッドが無いよ!」というエラーが発生する問題。
たとえばこれだとエラーになる。(n件のmemberを、membersという要素で包含している。)
<?xml version="1.0" encoding="UTF-8"?>
<menbers>
<member>
<id>1</id>
<id>name</id>
</member>
</menbers>
<?xml version="1.0" encoding="UTF-8"?>
<menbers type="array">
<member>
<id>1</id>
<id>name</id>
</member>
</menbers>
しばらく離れていたらすっかり忘れてる。
調査したことのメモ。
微妙に仕様変わってる。
基礎:ActiveRecordを使ってみる « UK STUDIO
検索して見つからない場合の戻り値:ActiveRecord find時の戻り - 忘れやすいのでメモ - Yahoo!ブログ
(検索方法によってnilだったり空の配列だったり、例外が投げられたり)
find_first()とfind_all()は無くなった:同じくActiveRecord find時の戻り - 忘れやすいのでメモ - Yahoo!ブログ
最大値等のSQLでいう集約関数:RDBMSの集約関数の結果をActiveRecordで取得する方法 - 森薫の日記
ランダムに1件取り出す:
そんな悲しい目をしないで » Blog Archive » Rails ActiveRecord でランダムにレコードを取得する方法
Mysql で、ランダムにレコードを取り出す方法 - kaeruspoon
(RAND()を使う方法は行数と同じだけRNAD()を実行するわけだから、行数が多い場合はしんどそう)
find_by_xxx()とfind_all_by_xxxについて:ActiveRecordで検索-find_by_* - うなの日記
tags: active-record, db, rails, ruby 0 コメント
メモ。
概要:Ruby on Rails : migration 機能でデータベーススキーマを変更する - WebOS Goodies
詳細:Ruby on Rails : migration 機能リファレンス - WebOS Goodies
データ型について等:FFTT : RailsのMigration
MySQLの数値型の:limitについて、上記参考サイトでは桁数を指定するように書いてあるが、手元のRails2.3.3ではバイト数を指定するようだ。
なのでbigintの場合は :limit => 8 にする。
参考:MySQL :: MySQL 5.1 リファレンスマニュアル :: 10.2 数値タイプ
備忘録として。
前提として、以前Railsを試したことがあるので、下記は事前にインストール済みだった。
rake aborted!そこで、PHP5.2のフォルダからlibmysql.dllをコピーしてきてRubyのbinフォルダに入れると解消した
Mysql::Error: Commands out of sync; you can't run this command now: SHOW TABLES
環境構築メモ。
Sinatraとは?