Ruby on Rails

docker compose + rails

2013年までの記事

Ruby 言語で開発された Web アプリケーション開発フレームワーク http://rubyonrails.com

<html> <div class="amazlet-box" style="margin-bottom:0px;"><div class="amazlet-image" style="float:left;margin:0px 12px 1px 0px;"><a href="http://www.amazon.co.jp/exec/obidos/ASIN/4274068668/r4wh-22/ref=nosim/" name="amazletlink" target="_blank"><img src="http://ecx.images-amazon.com/images/I/51Gibg-iYTL._SL160_.jpg" alt="RailsによるアジャイルWebアプリケーション開発 第4版" style="border: none;" /></a></div><div class="amazlet-info" style="line-height:120%; margin-bottom: 10px"><div class="amazlet-name" style="margin-bottom:10px;line-height:120%"><a href="http://www.amazon.co.jp/exec/obidos/ASIN/4274068668/r4wh-22/ref=nosim/" name="amazletlink" target="_blank">RailsによるアジャイルWebアプリケーション開発 第4版</a><div class="amazlet-powered-date" style="font-size:80%;margin-top:5px;line-height:120%">posted with <a href="http://www.amazlet.com/browse/ASIN/4274068668/r4wh-22/ref=nosim/" title="RailsによるアジャイルWebアプリケーション開発 第4版" target="_blank">amazlet</a> at 12.02.20</div></div><div class="amazlet-detail">Sam Ruby Dave Thomas David Heinemeier Hansson <br />オーム社 <br />売り上げランキング: 6190<br /></div><div class="amazlet-sub-info" style="float: left;"><div class="amazlet-link" style="margin-top: 5px"><a href="http://www.amazon.co.jp/exec/obidos/ASIN/4274068668/r4wh-22/ref=nosim/" name="amazletlink" target="_blank">Amazon.co.jp で詳細を見る</a></div></div></div><div class="amazlet-footer" style="clear: left"></div></div> </html>

教材

OSSオープンラボ「Ruby 研修用コンテンツ」の利用

「Webアプリケーションがはじめてなら、モデルを抜いて、コントローラとビューに集中するほうが」というアプローチ:

Mac + rvm で rails

since 2011-07-22

rvm にて詳述しました。

rvm 環境を使うなら sudo gem install せず rvmsudo gem install で統一するべきという話。

2013-04-07

Rails 3.2.13 を動かしてみる。

過去の環境構築で失敗しているらしく rails new が bundle エラーになるので下記のように回避:

$ rails new myrailsapp --skip-bundle
$ cd myrailsapp
$ rvmsudo bundle update
$ rails s

ブラウザで localhost:3000 を開く。

過去の情報

バージョンを指定してインストールするなら下記のように:

$ gem install -v=2.3.8 rails

sqlite3-ruby を入れようとしたら、エラーになった:

$ sudo gem install sqlite3-ruby
Password:
ERROR:  Could not find a valid gem 'sqlite3-ruby' (>= 0) in any repository
ERROR:  Possible alternatives: sqlite3-ruby

しかし、時間をおいてやり直したら成功した。 sqlite3-ruby ではなく sqlite3 という名前でよくなったらしい:

$ sudo gem install sqlite3-ruby
Fetching: sqlite3-1.3.3.gem (100%)
Building native extensions.  This could take a while...
Fetching: sqlite3-ruby-1.3.3.gem (100%)

#######################################################

Hello! The sqlite3-ruby gem has changed it's name to just sqlite3.  Rather than
installing `sqlite3-ruby`, you should install `sqlite3`.  Please update your
dependencies accordingly.

Thanks from the Ruby sqlite3 team!

<3 <3 <3 <3

#######################################################

Successfully installed sqlite3-1.3.3
Successfully installed sqlite3-ruby-1.3.3
2 gems installed
Installing ri documentation for sqlite3-1.3.3...
Installing ri documentation for sqlite3-ruby-1.3.3...
Installing RDoc documentation for sqlite3-1.3.3...
Installing RDoc documentation for sqlite3-ruby-1.3.3...

rails 3.2

since 2012-01-25

rails 3.2 が出ていた。

sudo gem install -v=3.2 rails

file 'lib' not found というメッセージが出たけど無事に終わった。

rails new test32

生成されるファイルに .gitignore とか .gitkeep が含まれている。もはや git は rails の標準VCS。。

rails s

ブラウザから localhost:3000 が出ることを確認した。

rake db:migrate
rake

デフォルトのテストが通った。

ruby 1.9.2 で rails 3

執筆 2010-08-25 / 更新 2010-10-17

勝手ビルドした ruby-1.9.2-p0 を Ubuntu Linux (9.04) に/usr/local/bin/rubyとしてインストール。3.0.1 が入った(2010年10月)。

$ sudo gem install rails

2010年8月には pre をつけないと怒られた。rails 3.0.0.rc2 が落ちてきた。

$ sudo gem install rails --pre

which すると /usr/local/bin/rails だと言われる。

sqlite3-ruby がないと怒られるので、入れる。ちなみに gem install のときに make が必要。

sudo aptitude install libsqlite3-dev make
sudo gem install sqlite3-ruby

デフォルトのアプリケーションで rake (test) を通す。

rails new testapp
cd testapp
rake db:migrate
rake

デフォルトのテストが通った。

Ubuntu で rvm + rails 3 beta

rvm で 1.9.1 を入れたものとして進める。

rvm 環境を使っているので sudo gem ではなくただの gem を使う。

$ gem install tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n

最後に下記のエラーが出る(後述)。

ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied - /home/nishi/.ri/cache/.doc_dirs
$ gem install rails --pre

Fetchエラーになったので再実行した。2回目で成功。 ただし、また上と同じ .doc_dirs のエラーが。

以下が回避方法になる。強引だが。。

$ sudo chmod -R 777 /home/nishi/.ri

$ gem install rails --pre
Successfully installed rails-3.0.0.beta
1 gem installed
Installing ri documentation for rails-3.0.0.beta...
Updating class cache with 2967 classes...
Installing RDoc documentation for rails-3.0.0.beta...

今度はうまくいった。これも。

$ gem install sqlite3-ruby
$ rails topscore
$ cd topscore/
$ rails s <= server の略。rails 2.x では script/server だった

ブラウザで localhost:3000 を開いて確認。

ここで openssh のエラーが出たら rvm の作業をやり直し。Ubuntu 9.10 で経験した。

$ rake db:migrate
$ rake test

こちらも問題なく動いた。

rvm + rails 3(beta3) と 2.3.5 の共存

$ rvmsudo gem install railties --pre
[sudo] password for nishi: 
Successfully installed i18n-0.3.7
Successfully installed activesupport-3.0.0.beta3
Successfully installed activemodel-3.0.0.beta3
Successfully installed actionpack-3.0.0.beta3
Successfully installed railties-3.0.0.beta3
5 gems installed
Installing ri documentation for i18n-0.3.7...
Installing ri documentation for activesupport-3.0.0.beta3...
Installing ri documentation for activemodel-3.0.0.beta3...
Installing ri documentation for actionpack-3.0.0.beta3...
Installing ri documentation for railties-3.0.0.beta3...
Updating class cache with 3542 classes...
Installing RDoc documentation for i18n-0.3.7...
Installing RDoc documentation for activesupport-3.0.0.beta3...
Installing RDoc documentation for activemodel-3.0.0.beta3...
Installing RDoc documentation for actionpack-3.0.0.beta3...
Installing RDoc documentation for railties-3.0.0.beta3...

この状態で 2.3.5 のアプリを作るには

$ rails _2.3.5_ app235

Ubuntu で ruby 1.8 + rails 2.x

Ubuntu 8.04 で rails 環境を作る。

Ubuntu 9.04 にアップグレードする。 script/server すると

no such file to load -- openssl

が出る。

http://railsforum.com/viewtopic.php?id=25874

$ sudo apt-get install libopenssl-ruby1.8

で解決。

rails 2.3.3

ぼちぼち ruby1.9 での利用も意識しつつ。

$ sudo gem1.8 install -v=2.3.3 rails

rails1.9 というコマンドを作る手順があるらしいが未確認。

2009年9月4日に 2.3.4 がリリースされ、db/seeds.rb 機能などが導入された。

rake タスク

rake で何ができるのか眺めてみる。(rails 2.3.3)

$ rake -T
(in /home/nishi/2009/rails/testapp)
rake db:abort_if_pending_migrations       # Raises an error if there are pending migrations
rake db:charset                           # Retrieves the charset for the current environment's database
rake db:collation                         # Retrieves the collation for the current environment's database
rake db:create                            # Create the database defined in config/database.yml for the current RAILS_ENV
rake db:create:all                        # Create all the local databases defined in config/database.yml
rake db:drop                              # Drops the database for the current RAILS_ENV
rake db:drop:all                          # Drops all the local databases defined in config/database.yml
rake db:fixtures:identify                 # Search for a fixture given a LABEL or ID.
rake db:fixtures:load                     # Load fixtures into the current environment's database.
rake db:migrate                           # Migrate the database through scripts in db/migrate and update db/schema.rb by invoking db:schema:dump. Target spec...
rake db:migrate:down                      # Runs the "down" for a given migration VERSION.
rake db:migrate:redo                      # Rollbacks the database one migration and re migrate up.
rake db:migrate:reset                     # Resets your database using your migrations for the current environment
rake db:migrate:up                        # Runs the "up" for a given migration VERSION.
rake db:reset                             # Drops and recreates the database from db/schema.rb for the current environment.
rake db:rollback                          # Rolls the schema back to the previous version.
rake db:schema:dump                       # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load                       # Load a schema.rb file into the database
rake db:sessions:clear                    # Clear the sessions table
rake db:sessions:create                   # Creates a sessions migration for use with ActiveRecord::SessionStore
rake db:structure:dump                    # Dump the database structure to a SQL file
rake db:test:clone                        # Recreate the test database from the current environment's database schema
rake db:test:clone_structure              # Recreate the test databases from the development structure
rake db:test:load                         # Recreate the test database from the current schema.rb
rake db:test:prepare                      # Check for pending migrations and load the test schema
rake db:test:purge                        # Empty the test database
rake db:version                           # Retrieves the current schema version number
rake doc:app                              # Build the RDOC HTML Files
rake doc:clobber_app                      # Remove rdoc products
rake doc:clobber_plugins                  # Remove plugin documentation
rake doc:clobber_rails                    # Remove rdoc products
rake doc:guides                           # Generate Rails guides
rake doc:plugins                          # Generate documentation for all installed plugins
rake doc:rails                            # Build the RDOC HTML Files
rake doc:reapp                            # Force a rebuild of the RDOC files
rake doc:rerails                          # Force a rebuild of the RDOC files
rake gems                                 # List the gems that this rails application depends on
rake gems:build                           # Build any native extensions for unpacked gems
rake gems:build:force                     # Force the build of all gems
rake gems:install                         # Installs all required gems.
rake gems:refresh_specs                   # Regenerate gem specifications in correct format.
rake gems:unpack                          # Unpacks all required gems into vendor/gems.
rake gems:unpack:dependencies             # Unpacks all required gems and their dependencies into vendor/gems.
rake log:clear                            # Truncates all *.log files in log/ to zero bytes
rake middleware                           # Prints out your Rack middleware stack
rake notes                                # Enumerate all annotations
rake notes:custom                         # Enumerate a custom annotation, specify with ANNOTATION=WTFHAX
rake notes:fixme                          # Enumerate all FIXME annotations
rake notes:optimize                       # Enumerate all OPTIMIZE annotations
rake notes:todo                           # Enumerate all TODO annotations
rake rails:freeze:edge                    # Lock to latest Edge Rails, for a specific release use RELEASE=1.2.0
rake rails:freeze:gems                    # Lock this application to the current gems (by unpacking them into vendor/rails)
rake rails:template                       # Applies the template supplied by LOCATION=/path/to/template
rake rails:unfreeze                       # Unlock this application from freeze of gems or edge and return to a fluid use of system gems
rake rails:update                         # Update both configs, scripts and public/javascripts from Rails
rake rails:update:application_controller  # Rename application.rb to application_controller.rb
rake rails:update:configs                 # Update config/boot.rb from your current rails install
rake rails:update:generate_dispatchers    # Generate dispatcher files in RAILS_ROOT/public
rake rails:update:javascripts             # Update your javascripts from your current rails install
rake rails:update:scripts                 # Add new scripts to the application script/ directory
rake routes                               # Print out all defined routes in match order, with names.
rake secret                               # Generate a crytographically secure secret key.
rake stats                                # Report code statistics (KLOCs, etc) from the application
rake test                                 # Run all unit, functional and integration tests
rake test:benchmark                       # Run tests for benchmarkdb:test:prepare / Benchmark the performance tests
rake test:functionals                     # Run tests for functionalsdb:test:prepare / Run the functional tests in test/functional
rake test:integration                     # Run tests for integrationdb:test:prepare / Run the integration tests in test/integration
rake test:plugins                         # Run tests for pluginsenvironment / Run the plugin tests in vendor/plugins/*/**/test (or specify with PLUGIN=name)
rake test:profile                         # Run tests for profiledb:test:prepare / Profile the performance tests
rake test:recent                          # Run tests for recentdb:test:prepare / Test recent changes
rake test:uncommitted                     # Run tests for uncommitteddb:test:prepare / Test changes since last checkin (only Subversion and Git)
rake test:units                           # Run tests for unitsdb:test:prepare / Run the unit tests in test/unit
rake time:zones:all                       # Displays names of all time zones recognized by the Rails TimeZone class, grouped by offset.
rake time:zones:local                     # Displays names of time zones recognized by the Rails TimeZone class with the same offset as the system local time
rake time:zones:us                        # Displays names of US time zones recognized by the Rails TimeZone class, grouped by offset.
rake tmp:cache:clear                      # Clears all files and directories in tmp/cache
rake tmp:clear                            # Clear session, cache, and socket files from tmp/
rake tmp:create                           # Creates tmp directories for sessions, cache, sockets, and pids
rake tmp:pids:clear                       # Clears all files in tmp/pids
rake tmp:sessions:clear                   # Clears all files in tmp/sessions
rake tmp:sockets:clear                    # Clears all files in tmp/sockets

generate model の逆の処理

$ ./script/generate model product hoge:string

をやり直したいとき destroy model が使える。

$ ./script/destroy model product
    notempty  db/migrate
    notempty  db
          rm  db/migrate/20090909075610_create_products.rb
          rm  test/fixtures/products.yml
          rm  test/unit/product_test.rb
          rm  app/models/product.rb
    notempty  test/fixtures
    notempty  test
       rmdir  test/unit
    notempty  test
       rmdir  app/models
    notempty  app

ちなみに db:migrate をやり直したければ db:migrate VERSION=0 など。

mime-type

m3u とか pls とかの MIME-Type audio/x-mpegurl を指定するには?

config/initializers/mime_types.rb に書けばよい?

Mime::Type.register "audio/x-mpegurl", :m3u

第2引数は format に対応するらしい。

# then in your controller action
def show
  respond_to do |format|
    format.m3u {
      render :text => "http://hoge.com/hoge.mp3", :mime_type => Mime::Type["audio/x-mpegurl"]  
    }
  end
end

render を書かないと /foos/bar.m3u ⇒ /app/views/foos/bar.m3u.erb

ちなみに .pls はこんな感じ。MIME-Type は "audio/x-scpls" らしい。

[playlist]
numberofentries=1
File1=http://server.com:80
Title1=server.com - The world's hoge radio 
Length1=-1
Version=2

(to be written)

ruby_on_rails.txt · 最終更新: 2022/12/24 15:20 by Takuya Nishimoto
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0