Rails Tutorial 6th Edition Learning Summary Chapter 4

Overview

This article deepens my understanding by writing a Rails tutorial commentary article to further solidify my knowledge It is part of my study. In rare cases, ridiculous content or incorrect content may be written. Please note. I would appreciate it if you could tell me implicitly ...

Source Rails Tutorial 6th Edition

What to do in this chapter

Learn about Ruby grammar and structure for the future.

Motivation

While I knew the convenience of being able to write code to some extent using Rails without knowing much about Ruby If you don't know about Ruby, development will be inefficient and your code will be limited. You will also learn about Ruby itself here.

Create and work on topic branches as usual.

$ git checkout -b rails-flavored-ruby
Switched to a new branch 'rails-flavored-ruby'

Built-in helper

It was written inside application.html.erb created in the previous chapter

<%= stylesheet_link_tag 'application', media: 'all','data-turbolinks-track': 'reload' %>

I will also study the grammar used here. The stylesheet_link_tag is the Rails built-in helper.

Custom helper

In Rails, in addition to built-in functions, you can define your own and use field functions. This time, if you do not give any value to the site title with the provide method, the default title will be returned. Let's create a function.

Because it is a helper that I want to use in the layout file application.html.erb Define in application helper

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
      page_title + " | " + base_title
    end
  end
end

Strings and methods

We will proceed with learning using the Rails console.

In my case, I got an error and couldn't start it at first. Examples and countermeasures are listed for reference.

Error that appeared at startup

FATAL: Listen error: unable to monitor directories for changes.
Visit https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers for info on how to fix this

Reference site https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers

What to do when rails console cannot be started ("FATAL: Listen error" error edition)

If the startup is successful Such a console launches.

Running via Spring preloader in process 6472
Loading development environment (Rails 6.0.3)
>> 

Just like the terminal, you can use the up arrow key to get the command you hit before, so there's no reason not to use it.

String

Let's take up what I personally feel is important.

-Character strings can be created by enclosing them in "" (double quotes).

-Variables can be expanded in a character string by enclosing them in # {}.

-A character string can also be created by enclosing it in'' (single quotes).

-Expression expansion is not possible with a character string enclosed in single quotes.

・ Single quotes are convenient when you want to display special characters such as # as they are.

Exercise

1.

>> city = "Shinjuku ward"
=> "Shinjuku ward"
>> prefecture = "Tokyo"
=> "Tokyo"
>> puts prefecture + " " + city
Shinjuku-ku, Tokyo
=> nil
>> puts prefecture + "\t" + city                                                                     
Shinjuku-ku, Tokyo
=> nil
>> puts prefecture + '\t' + city                                                                      
Tokyo\t Shinjuku Ward
=> nil

Passing objects and messages

Here too, I will summarize the important parts.

・ Ruby is an object └ Character strings, just numbers, null are also treated as objects

-It is customary for Ruby methods to return logical values if they are suffixed with?

・ Ruby is els if, not else if! ← Be careful because you often make mistakes and throw useless errors ()

-In Ruby, you can use subsequent if and unless statements. → The code is easy to read and concise and very convenient

-Any object such as a character string or nil can be negated twice by prefixing it with two!

>> !"If you deny it once, it will be reversed."
=> false
>> !!"You can make the result logical value by denying it twice."
=> true

The easiest thing to understand is to display the class of the object with the class method. You can find the class of an object by setting it to .class.

>> nil.class
=> NilClass
>> "".class
=> String
>> 12.class
=> Integer

Always have a class like this

Exercise
>> "racecar".length
=> 7
>> "racecar".reverse
=> "racecar"
>> s= "racecar"
=> "racecar"
>> s == s.reverse
=> true
>> puts "It's a palindrome!" if s == s.reverse
It's a palindrome!
=> nil
>> s = "onomatopoeia"
=> "onomatopoeia"
>> puts "It's a palindrome!" if s == s.reverse
=> nil

Method definition

It ’s very simple to do here as well. Summarize only the main points.

-Methods can contain default values. (Arguments can be omitted if there is a default value)

-Ruby can be described by omitting the parentheses () of the method argument. ← If you don't understand this, the code in the following chapters will be unclear ...

-Ruby has an implicit return value in the method. (Implicitly returns the last expression in the method without a return.)

>> def show_message
>> "Nice to meet you!"
>> end
=> :show_message
>> show_message
=> "Nice to meet you!"

It may be a little confusing, but when I execute the show_message method, it returns "Nice to meet you!" It can be seen that even if the return value is not specified in the return statement, the evaluation content of the last expression in the method is returned as an implicit return value.

Exercise
>> def palindrome_tester(s)
>> if s == s.reverse
>> puts "It's a palindrome!"
>> else 
>> puts "It's not a palindrome!"
>> end
>> end
=> :palindrome_tester
>> palindrome_tester("racecar")
It's a palindrome!
=> nil
>> palindrome_tester("onomatopoeia")
It's not a palindrome!
=> nil
>> palindrome_tester("racecar").nil?
It's a palindrome!
=> true

title helper again

The full_title method is written in Application Helper. module Application Helper is a function to group methods together. Those that can use that module by using the include module name

It's one of the useful features of Rails, and the helper module is loaded without permission, so you don't have to bother to include it. Can be used.

ApplicationHelper is can also be used in any view for the common helper module of all views. Super convenient.

Other data structures

Array and range operators

Here is also a summary of the points.

・ Various methods such as sort, reverse, shuffle can be used for arrays. Those methods just return a value, the contents of the array do not change To rewrite the contents as it is, add! At the end of the method and use "destructive method".

-You can add an element to the end of the array by using push or <<.

・ If 0..4 is specified, 0,1,2,3,4 is returned. (Range object)

・ Although it is a little complicated, by specifying the range object and -1 as the subscript of the array

>> a[2..-1]
=> [2, 3, 4, 5, 6, 7, 8, 9]

This kind of operation can be realized The range object at this time is specified from 2 to the very end of the array.

Exercise
>> a = "A man,a plan,a canal,Panama".split(",")
=> ["A man", "a plan", "a canal", "Panama"]
>> s = a.join
=> "A mana plana canalPanama"
>> palindrome_tester(s.split.join.downcase)
It's a palindrome!
=> nil
>> array =("a".."z").to_a
=> ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
>> array[7]
=> "h"
>> array[-7]
=> "t"

block

Ruby's features are very convenient but difficult to block

(1..5).each { |i| puts 2 * i }When I try to read it gently in Japanese


 Do 2 x that number for each number from 1 to 5. … It's hard to understand ()
 You put the range objects 1..5 one by one, put them in the variable i, and put the result of 2 * i.
 Difficult to explain ...

 If you implement this without using blocks

puts 2 * 1 2 => nil

puts 2 * 2 4 => nil

puts 2 * 3 6 => nil

puts 2 * 4 8 => nil

puts 2 * 5 10 => nil


 You can reduce the amount of code by using blocks + you can apply it. In other words, it's super convenient and important. that's all…

 times → Repeat the processing in the block the specified number of times.

 each → Apply the processing in the block to each element such as array and range object.

 map → Apply the processing in the block to each element such as array and range object, and return the result.

 If you understand this and use blocks, you can understand the blocks in the tutorial to some extent.

 The description of the test code of minitest used in the tutorial is also a block.

test "it is a test" do

end

 In this description, the part surrounded by do end is a block.

##### Exercise
1.

(0..16).each { |i| puts i**2} 0 1 4 9 16 25 36 49 64 81 100 121 144 169 196 225 256 => 0..16


 2. This is a detour if you use map as instructed in the problem statement

 How to not use map

def yeller(strings) strings.join.upcase end => :yeller

yeller(['o','l','d']) => "OLD"


 how to use map

def yeller(strings) s = strings.map { |string| string.upcase} s.join end => :yeller

yeller(['o','l','d']) => "OLD"


3.

def random_subdomain ("a".."z").to_a.shuffle[0..7].join end => :random_subdomain

random_subdomain => "gimfnslj"


4.

def string_shuffle(s) s.split('').shuffle.join end => :string_shuffle

string_shuffle("foobar") => "bforao"


#### Hashes and symbols
 I will omit the explanation here, but be careful of only one

 Hash abbreviation

#### **`params = { name: "Michael", email: "[email protected]"}`**

Don't forget that this only uses the symbols : name and `` `: email``` as keys. Because I didn't really understand In a later chapter params [: user] [: email] Why is it a symbol when it is written? Don't let that happen ...

Exercise
>> numbers = { "one" => "uno", "two" => "dos", "three" => "tres"}
=> {"one"=>"uno", "two"=>"dos", "three"=>"tres"}
>> numbers.each { |key,value| puts "'#{key}'Spanish is'#{value}'"}
'one'Spanish is'uno'
'two'Spanish is'dos'
'three'Spanish is'tres'
=> {"one"=>"uno", "two"=>"dos", "three"=>"tres"}
>> person1 = { first: "Shinzo", last:"Abe" }
=> {:first=>"Shinzo", :last=>"Abe"}
>> person2 = { first: "yoshihide", last:"suga" }                                                      
=> {:first=>"yoshihide", :last=>"suga"}
>> person3 = { first: "Taro", last:"Aso" }                                                            
=> {:first=>"Taro", :last=>"Aso"}
>> params = { father: person1, mother: person2, child: person3}
=> {:father=>{:first=>"Shinzo", :last=>"Abe"}, :mother=>{:first=>"yoshihide", :last=>"suga"}, :child=>{:first=>"Taro", :last=>"Aso"}}
>> params[:father][:first]
=> "Shinzo"
>> user = { name:"take", email:"[email protected]", password_digest: ("a".."z").to_a.shuffle[0..15].join}
=> {:name=>"take", :email=>"[email protected]", :password_digest=>"mkadrptqhysfnoec"}
  1. Overwrite if the key exists, add a new Hash method if it does not exist The value of "b" is overwritten because the key "b" exists In other words
>> { "a" => 100, "b" => 200 }.merge({ "b" => 300 })
=> {"a"=>100, "b"=>300}

CSS again

Here, I will try to decipher the meaningless line written in the layout file

stylesheet_link_tag 'application', media: 'all',
                                   'data-turbolinks-track': 'reload'

This line is -The parentheses when calling the method may be omitted. -The {} of the hash of the last argument when calling the method may be omitted. It is simplified using the rule. If you write without simplification

stylesheet_link_tag ('application', {media: 'all',
                                   'data-turbolinks-track': 'reload'})

Will be.

Classes in Ruby

constructor

Usually, an instance of some class is created using new. Example user = User.new This is called a named constructor and calls the new method on the class name. But some classes can be instantiated differently Example "Hello" a = [1,2,3]

0..5


 These are called literal constructors
 These are instances of the String, Array, and Range classes, respectively.

##### Exercise
 1 ... operator → 0..10 etc.

2.

Range.new(1,10) => 1..10

3.

(0..10) == Range.new(0,10)
=> true


#### Class inheritance
 Omitted as it is described in detail in the tutorial

##### Exercise
 1. All inherit the Object class.

Hash.superclass => Object

Range.superclass => Object

Symbol.superclass => Object


2.

class Word < String def palindrome? self == reverse end end => :palindrome?

s = Word.new("Newsprint") => "Newsprint"

s.palindrome? => true


#### Change built-in class
 Built-in classes that exist in Ruby
 Can be expanded. You shouldn't extend built-in classes unless you have a good reason to do so
 Rails adds some commonly used convenience methods to its built-in classes.

##### Exercise
 Try 1,2,3 at the same time.

```irb
>> class String
>> def palindrome?
>> downcase == downcase.reverse
>> end
>> def shuffle
>> split('').shuffle.join
>> end
>> end
=> :shuffle
>> "racecar".palindrome?
=> true
>> "racecar".shuffle
=> "reaarcc"

Controller class

image.png From Rails Tutorial 6th Edition https://railstutorial.jp/chapters/rails_flavored_ruby?version=6.0#fig-static_pages_controller_inheritance

The inheritance structure of the StaticPages controller created in Chapter 3 looks like this

Exercise
takemo-admin:~/environment/toy_app (master) $ cd ../sample_app/
takemo-admin:~/environment/sample_app (rails-flavored-ruby) $ cd ../toy_app/
takemo-admin:~/environment/toy_app (master) $ rails c
Running via Spring preloader in process 13820
Loading development environment (Rails 6.0.3)
>> user = User.new
   (1.4ms)  SELECT sqlite_version(*)
=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil>
>> user.class.superclass
=> ApplicationRecord(abstract)
>> user.class.superclass.superclass
=> ActiveRecord::Base
>> user.class.superclass.superclass.superclass
=> Object

User class

Here too, I will summarize the points that I personally want to remember.

-Attr_accessor: Defines accessors (getters, setters) for attributes. By defining this, you can assign a value to an instance and receive a value from the instance.

-Variable with @: Instance variable. If defined in the controller, it can be used in the view and can be used in common within the same class.

-Initialize method: Called automatically when an instance is created by the new method. Used for initializing instance variables.

-Read a file with require, load a module with include.

Exercise
class User
  attr_accessor :first_name, :last_name, :email

  def initialize(attributes = {})
    @first_name  = attributes[:first_name]
    @last_name = attributes[:last_name]
    @email = attributes[:email]
  end
  def full_name
    @first_name + "\s" + @last_name
  end
  def formatted_email
    "#{full_name} <#{@email}>"
  end
end
  def alphabetical_name
    @last_name + ",\s" + @first_name
  end
>> example.full_name.split == example.alphabetical_name.split(', ').reverse
=> true

To the previous chapter

To the next chapter

Recommended Posts

Rails Tutorial 6th Edition Learning Summary Chapter 7
Rails Tutorial 6th Edition Learning Summary Chapter 4
Rails Tutorial 6th Edition Learning Summary Chapter 9
Rails Tutorial 6th Edition Learning Summary Chapter 6
Rails Tutorial 6th Edition Learning Summary Chapter 5
Rails Tutorial 6th Edition Learning Summary Chapter 2
Rails Tutorial 6th Edition Learning Summary Chapter 3
Rails Tutorial 6th Edition Learning Summary Chapter 8
Rails Tutorial (4th Edition) Summary
Rails Tutorial (4th Edition) Memo Chapter 6
Rails Tutorial Chapter 3 Learning
Rails Tutorial Chapter 4 Learning
Rails Tutorial Chapter 1 Learning
Rails Tutorial Chapter 2 Learning
Rails Tutorial 4th Edition: Chapter 1 From Zero to Deployment
[Rails Struggle/Rails Tutorial] Summary of Rails Tutorial Chapter 2
rails tutorial chapter 10 summary (for self-learning)
rails tutorial Chapter 6
rails tutorial Chapter 1
rails tutorial Chapter 7
rails tutorial Chapter 5
rails tutorial Chapter 10
rails tutorial Chapter 9
rails tutorial Chapter 8
Rails Tutorial Chapter 0: Preliminary Basic Knowledge Learning 5
Rails tutorial (6th edition) Follow/unfollow background operation
Rails Tutorial Chapter 5 Notes
Rails Tutorial Chapter 10 Notes
Rails Tutorial Chapter 3 Notes
[Rails] Learning with Rails tutorial
Rails Tutorial Memorandum (Chapter 3, 3.1)
Rails Tutorial Chapter 4 Notes
Rails Tutorial Chapter 8 Notes
Rails Tutorial Memorandum (Chapter 3, 3.3.2)
Rails tutorial (6th edition) Background operation of profile editing
[Rails Tutorial Chapter 4] Rails-flavored Ruby
Rails tutorial (6th edition) Background operation of login function
Rails tutorial (6th edition) Background operation of password reset function
[Rails Tutorial Chapter 5] Create a layout
Chewing Rails Tutorial [Chapter 2 Toy Application]
rails tutorial
rails tutorial
rails tutorial
rails tutorial
Rails Tutorial (6th Edition) -Explanation of background operation for each function-
rails tutorial
rails tutorial
rails tutorial
[Rails Struggle/Rails Tutorial] Summary of Heroku commands
Rails tutorial (6th edition) Background operation of the posting function of the micro post
A summary of only Rails tutorial setup related
Rails tutorial test
[Rails Struggle/Rails Tutorial] What you learned in Rails Tutorial Chapter 3
[Ruby on Rails] Rails tutorial Chapter 14 Summary of how to implement the status feed
Rails tutorial memorandum 1
Rails Tutorial Chapter 1 From Zero to Deployment [Try]
Rails learning day 3
Rails tutorial memorandum 2
Rails learning day 4
Rails 6.0 Routing Summary
Rails learning day 2