LoginSignup
12
13

More than 5 years have passed since last update.

あとでもっかい試す用 - Ruby on Rails 4.0 チュートリアル - 第四章

Posted at

Ruby on Rails チュートリアル 実例を使ってRailsを学ぼう 第4章を見ながらやったことを、あとでもう一度できるようにまとめます!!第四章!!

第四章の説明

  • Rubyの基礎知識を学ぶ

full_titleヘルパーを定義する

ヘルパー作成

$ subl app/helpers/application_helper.rb

module ApplicationHelper

  # ページごとの完全なタイトルを返します。
  def full_title(page_title)
    base_title = "Ruby on Rails Tutorial Sample App"
    if page_title.empty?
      base_title
    else
      "#{base_title} | #{page_title}"
    end
  end
end

レイアウトをfull_titleヘルパーを使って修正

Homeページは、「Ruby on Rails Tutorial Sample App」の後に「|Home」を表示しないようにする。

$ subl app/views/layouts/application.html.erb 
<!DOCTYPE html>
<html>
<head>
-  <title>Ruby on Rails Tutorial Sample App | <%= yield(:title) %></title>
+  <title><%= full_title(yield(:title)) %></title>
   <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
   <%= javascript_include_tag "application", "data-turbolinks-track" => true %>

テストを作成

$ subl spec/requests/static_pages_spec.rb

     it "should have the right title" do
       visit '/static_pages/home'
-      expect(page).to have_title("Ruby on Rails Tutorial Sample App | Home")
+      expect(page).to have_title("Ruby on Rails Tutorial Sample App")
+    end
+
+    it "should not have a custom page title" do
+      visit '/static_pages/home'
+      expect(page).not_to have_title("|Home")
     end
   end

テストを実行

$ bundle exec rspec spec/requests/static_pages_spec.rb
=> 失敗

テストをパスするように修正

provideを削除

$ subl app/views/static_pages/home.html.erb 

- <% provide(:title, 'Home') %>
  <h1>Sample App</h1>
  <p>

コメント

ソースコード中の#から行の終わりまではコメントになる。

# ページごとの完全なタイトルを返します。
def full_title(page_title)
  .
  .
  .
end

文字列

$ rails c
"Loading development environment (Rails 4.0.0)


irb(main):001:0> "" # 空の文字列
=> ""
irb(main):002:0> "foo" # 空でない文字列
=> "foo"


irb(main):003:0> "foo" + "bar" # 文字列の結合
=> "foobar"


irb(main):004:0> first_name = "Michael" #変数割り当て
=> "Michael"
irb(main):005:0> "#{first_name} Hartl" # 文字列の式展開
=> "Michael Hartl"


irb(main):006:0> first_name = "Michael"
=> "Michael"
irb(main):007:0> last_name = "Hartl"
=> "Hartl"
irb(main):008:0> first_name + " " + last_name
=> "Michael Hartl"
irb(main):009:0> "#{first_name} #{last_name}" # 式展開による同等のコード
=> "Michael Hartl"

出力

$ rails c
"Loading development environment (Rails 4.0.0)


irb(main):010:0> puts "foo" # puts は文字列を出力してnilを返す。文字列の最後に改行を追加する。
foo
=> nil


irb(main):011:0> "foo" # printはputsとほとんど同じ。文字列の最後に改行を追加しないところが違う。
foo=> nil

シングルクォート

シングルクォートで囲んだ文字列は式展開しない。

irb(main):012:0> foo = "test"
=> "test"
irb(main):013:0> '#{foo} bar'
=> "\#{foo} bar"

バックスラッシュをそのまま保持するときに便利

irb(main):015:0> 'Newlines (\n) and tabs (\t) both use the backslash character \.'
=> "Newlines (\\n) and tabs (\\t) both use the backslash character \\."

オブジェクトとメッセージ受け渡し

irb(main):016:0> "foobar".length # 文字列に"length"というメッセージを渡す。lengthメソッドが実行される 。
=> 6

empty?メソッドを呼び出す。論理値を返すメソッドの名前には最後に?をつけるのがrubyのやり方だ。

irb(main):017:0> "foobar".empty?
=> false

# empty?は制御フローで使える。
irb(main):018:0> s = "foobar"
=> "foobar"
irb(main):019:0> if s.empty?
irb(main):020:1>   "The string is empty"
irb(main):021:1> else
irb(main):022:1*   "The string is nonempty"
irb(main):023:1> end
=> "The string is nonempty"

論理値は、&&(and), ||(or), !(not) で論理値をつなげる。

nilもオブジェクト。

irb(main):024:0> nil.to_s
=> ""

irb(main):025:0> nil.to_s.empty? # メッセージを連鎖
=> true

if が真のときだけ実行する書き方

irb(main):027:0> x = "a"
=> "a"
irb(main):028:0> puts "x is not empty" if !x.empty?
x is not empty
=> nil


irb(main):029:0> x = ""
=> ""
irb(main):030:0> puts "x is not empty" if !x.empty?
=> nil

オブジェクトそのものの論理値がfalseになるのはnilだけ。

メソッド定義

# メソッドを定義
irb(main):031:0> def string_message(string)
irb(main):032:1>   if string.empty?
irb(main):033:2>     "It's an empty string!"
irb(main):034:2>   else
irb(main):035:2*     "The string is nonempty."
irb(main):036:2>   end
irb(main):037:1> end
=> nil

# メソッドを使う1
irb(main):038:0> puts string_message("")
It's an empty string!
=> nil

# メソッドを使う2
irb(main):039:0> puts string_message("foobar")
The string is nonempty.
=> nil

配列と範囲演算子

配列

# 文字列を空白で分割して配列にする
irb(main):040:0> "foo bar     baz".split 
=> ["foo", "bar", "baz"]

# 分割する文字列を指定する場合
irb(main):041:0> "fooxbarxbazx".split('x')
=> ["foo", "bar", "baz"]

# 配列にアクセス
irb(main):042:0> a = "fooxbarxbazx".split('x')
=> ["foo", "bar", "baz"]
irb(main):046:0> a[0] # 角かっこでアクセスできる
=> "foo"

配列のメソッド

irb(main):051:0> a
=> ["foo", "bar", "baz"]

irb(main):052:0> a.sort
=> ["bar", "baz", "foo"]

irb(main):053:0> a.reverse
=> ["baz", "bar", "foo"]

irb(main):054:0> a.shuffle
=> ["foo", "baz", "bar"]

# sort!を実行するとaの内容が変更される
irb(main):055:0> a.sort!
=> ["bar", "baz", "foo"]

irb(main):056:0> a
=> ["bar", "baz", "foo"]

# 配列に値を追加
irb(main):057:0> a.push("aaa")
=> ["bar", "baz", "foo", "aaa"]

irb(main):058:0> a << "bbb"
=> ["bar", "baz", "foo", "aaa", "bbb"]

irb(main):059:0> a << "ccc" << "ddd"
=> ["bar", "baz", "foo", "aaa", "bbb", "ccc", "ddd"]

# 配列を結合
irb(main):060:0> a.join
=> "barbazfooaaabbbcccddd"

# 結合文字をつけて配列を結合
irb(main):061:0> a.join(",")
=> "bar,baz,foo,aaa,bbb,ccc,ddd"

範囲指定

irb(main):064:0> (0..9).to_a # 範囲にメソッドを指定する場合かっこで囲む
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

範囲は配列の要素を取り出すときに便利

irb(main):065:0> a = %w[foo bar baz quux] 
=> ["foo", "bar", "baz", "quux"]

irb(main):066:0> a[0..2]
=> ["foo", "bar", "baz"]

# 2から最後まで
irb(main):069:0> a[2..(a.length-1)]
=> ["baz", "quux"]

ブロック

irb(main):071:0> (1..5).each { |i| puts 2 * i }
2
4
6
8
10
=> 1..5 

ハッシュとシンボル

=> {}
irb(main):073:0> user["first_name"] = "Michael" # キー: "first_name"、値: "Michael"
=> "Michael"
irb(m   ain):074:0> user["last_name"] = "Hartl" # キー: "last_name"、値: "Hartl"
=> "Hartl"
irb(main):075:0> user # ハッシュのリテラルな表記
=> {"first_name"=>"Michael", "last_name"=>"Hartl"}

ハッシュロケット(=>)を使った書き方

irb(main):076:0> user = { "first_name" => "Michael", "last_name" => "Hartl" }
=> {"first_name"=>"Michael", "last_name"=>"Hartl"}

キーにシンボルを使う

irb(main):077:0> user = { :name => "Michael Hartl", :email => "michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"michael@example.com"}

ハッシュロケットを使わない & シンボルを使った書き方

irb(main):078:0> h2 = { name: "Michael Hartl", email: "michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"michael@example.com"}

ネストしたハッシュ

irb(main):079:0> params = {}
=> {}

irb(main):080:0> params[:user] = { name: "Michael Hartl", email: "mhartl@example.com" }
=> {:name=>"Michael Hartl", :email=>"mhartl@example.com"}

irb(main):081:0> params
=> {:user=>{:name=>"Michael Hartl", :email=>"mhartl@example.com"}}

レイアウトにCSSを追加する行をもう一度読む

<%= stylesheet_link_tag "application", media: "all",
                        "data-turbolinks-track" => true %>
  • stylesheet_link_tag の丸括弧は省略されている
  • 「 media: "all", "data-turbolinks-track" => true 」の部分はハッシュ。関数呼び出しの最後の引数がハッシュの場合、波括弧を省略できる。
  • "data-turbolinks-track" => true の部分でハッシュロケットを使ってるのは、シンボルではハイフンが使用できない為
  • 一行の文字数は80文字にするために改行してる

Rubyのクラス

クラスをつくってみる

irb(main):089:0> class Word
irb(main):090:1>   def palindrome?(string)
irb(main):091:2>     string == string.reverse
irb(main):092:2>   end
irb(main):093:1> end
=> nil

irb(main):094:0> w = Word.new
=> #<Word:0x007f7f6a009768>
irb(main):095:0> w.palindrome?("foobar")
=> false
irb(main):096:0> w.palindrome?("level")
=> true

Stringを継承させて作り直す

irb(main):001:0> class Word < String  
irb(main):002:1>   def palindrome?
irb(main):003:2>     self == self.reverse 
irb(main):004:2>    end
irb(main):005:1>  end
=> nil

irb(main):006:0> s = Word.new("level") 
=> "level"
irb(main):007:0> s.palindrome?
=> true
irb(main):008:0> s.length
=> 5

組込みクラスの変更

rubyでは、組み込みの基本クラスの拡張ができる。

irb(main):011:0> class String
irb(main):012:1>   def palindrome?
irb(main):013:2>     self == self.reverse
irb(main):014:2>   end
irb(main):015:1> end
=> nil
irb(main):016:0> "deified".palindrome?
=> true

ただし、「真に正当な理由」がない限り、組み込みクラスにメソッドを追加することは無作法であると考えられている。

ユーザークラス

$ subl example_user

class User
  # @nameと@emailのアクセサを作成する
  attr_accessor :name, :email

  # attributes引数の初期値は空のハッシュ
  def initialize(attributes = {})
    # attributesにそれぞれのシンボルに対応する値が設定されていない場合は、nilがインスタンス変数に入る
    @name  = attributes[:name]
    @email = attributes[:email]
  end

  def formatted_email
    "#{@name} <#{@email}>"
  end
end

rails consoleで使ってみる

$ rails c
Loading development environment (Rails 4.0.0)
irb(main):001:0> require './example_user'
=> true
irb(main):002:0> example = User.new
=> #<User:0x007fa78cfdabe8 @name=nil, @email=nil>
irb(main):003:0> example.name
=> nil
irb(main):004:0> example.name = "Example User"
=> "Example User"
irb(main):005:0> example.email = "user@example.com"
=> "user@example.com"
irb(main):006:0> example.formatted_email
=> "Example User <user@example.com>"
12
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
13