AR삽질러

Rails 一日一つメソッド (Day47) Ruby - self 본문

Ruby/RubyOnRails-日本語

Rails 一日一つメソッド (Day47) Ruby - self

아랑팡팡 2024. 3. 6. 15:52
728x90

 

Rails 一日一つメソッド (Day47) Ruby - self

 

1. selfとは

 - selfは、Rubyのキーワードで、現在のオブジェクトを表したり、オブジェクトの属性に接近したり、メソッドを呼び出したり様々な機能を行う。

 

2. selfの例

2-1. オブジェクトに接近

class User
	attr_accessor :name
    
    def initializa(name)
    	@name = name
    end
    
    def display_name
    	puts "私の名前は #{self.name}です!"
    end
end
user = User.new("Arang")
user.display_name # "私の名前は Arangです!"

 

self.nameは 現在のUserオブジェクトの name属性を表し、display_nameを呼び出したら、オブジェクトの名前の出力できる。

 

2-2. Userの数

class User
	@@user_count = 0
    
    def self.increment_user_count
    	@@user_count += 1
        puts "Userの数は #{self.user_count}です!"
    end
    
    def self.user_count
    	@@user_count
    end
end
User.increment_user_count  # " User数は 5です!"

 

@@user_count = 0

 - @@user_countを初期化し、全てのインスタンスで同じ値を持つことができる。

self.increment_user_count

 - Userが登録される時に、@@user_countが 1増加し、その値を出力する。

self.user_count

 - 登録されているUser数を返還する。

 

2-3) PasswordとPassword Confirmation検証

class User < ApplicationRecord
	validate :password_confirmation_match
    
    def password_confirmation_match
    	if self.password.present? && self.password_confirmation.present? && self.password != password_confirmation
			errors.add(:password_confirmation, "Passwordと一致しません。。")
        end
    end
end

 

self.passwordとself.password_confirmationは、現在のオブジェクトの属性(Password、password _confiramtion)に接近し、現在のオブジェクトのPasswordと一致しない場合、errorsを発生させる。

728x90
반응형
LIST