I'm a beginner at Ruby.
We're going through chapter 9 of the Rails tutorial.
I wonder why the following code members do not become User.remember.
I thought that all member functions inside the class should be defined as User. or self. If so, why is it wrong?
I look forward to your kind cooperation.
I don't think I understand object-oriented things, so I'm reflecting on myself and studying, but I'm not sure.
List 9.3: green to add the Remember method to the User model
class User<ApplicationRecord
attr_accessor:remember_token
before_save {self.email=email.downcase}
values:name,presence:true,length:{maximum:50}
VALID_EMAIL_REGEX=/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
values:email, presence:true, length:{maximum:255},
format: {with:VALID_EMAIL_REGEX},
unity: {case_sensitive:false}
has_secure_password
values:password,presence:true,length:{minimum:6}
# return the hash value of a passed string
def User.digest(string)
cost=ActiveModel::SecurePassword.min_cost?BCrypt::Engine::MIN_COST:
BCrypt::Engine.cost
BCrypt::Password.create(string, cost:cost)
end
# return a random token
def User.new_token
SecureRandom.urlsafe_base64
end
# store users in the database for persistent sessions
Why is it not defremember#emmemo⦆User.remember?
self.remember_token=User.new_token
update_attribute(:remember_digest,User.digest(remember_token))
end
end
[Note] The answers below contain a little difficult content.Ruby beginners may not be able to understand much right now.Don't force yourself to understand and try reading it again later.
To create a class method, define it with the def class name.method name
or def self.method name
.On the other hand, if you want to create an instance method, only the def method name
.
Ruby's most methods are instance methods because they change the behavior of the method depending on the absence of an instance (such as what is in the instance variable).However, you may want to create a method that does not depend on a particular instance.That's when class methods are created.The big difference from instance methods is that class methods can be invoked without having to create an instance.
Now, in Ruby, the class method is the unique method of the class (the instance method of the singular class). singular method is defined as an instance method within the singular class class<<object
or by the def object.method name
Within the class name
, if you write class name
, it refers to the object itself (in Ruby, the class is also an object).Also, in the context directly below it, self
is also an object of the class itself.In other words, the def class name.method name
or def self.method name
defines a unique method for the class itself.As I said earlier, the class method was unique.So this is how you create class methods.
You can also write within class<<class name
or class<<self
See the official documentation for more information.
Note: https://docs.ruby-lang.org/ja/latest/doc/spec=2fdef.html#class_method
© 2024 OneMinuteCode. All rights reserved.