我正在关注Michael Hartl的RoR教程,它涵盖了密码加密的基础知识.这是目前的用户模型:
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email,: password, :password_confirmation
email_regex = /^[A-Za-z0-9._+-]+@[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+[A-Za-z]$/
#tests for valid email addresses.
validates :name, :presence => true,
:length => {:maximum => 50}
validates :email, :presence => true,
:format => {:with => email_regex},
:uniqueness => {:case_sensitive => false}
validates :password, :presence => true,
:length => {:maximum => 20, :minimum => 6},
:confirmation => true
before_save :encrypt_password
private
def encrypt_password
self.encrypted_password = encrypt(password)
end
def encrypt(string)
string
end
end
Run Code Online (Sandbox Code Playgroud)
我发布了一个关于before_save不工作的上一个问题,事实证明我不小心做的是将我的encrypt_password写成:
def …Run Code Online (Sandbox Code Playgroud) 在可能的情况下,有一个约定可以在其实例变量上引用对象的属性.Ruby中实用的面向对象设计说:
始终将实例变量包装在访问器方法中,而不是直接引用变量...
这是一个例子,我已经解释过了:
class Gear
attr_reader :chainring, :cog
...
def ratio
# this is bad
# @chainring / @cog.to_f
# this is good
chainring / cog.to_f
end
Run Code Online (Sandbox Code Playgroud)
我看到使用实例变量创建新对象的最常见方法是:
class Book
attr_accessor :title
def initialize(title)
@title = title
end
end
Run Code Online (Sandbox Code Playgroud)
@title=直接访问实例变量title.假设我们遵循'属性over instance variable'约定,是否更适合使用self.title=,这会告诉对象自己发送消息title=,从而使用属性write方法直接对实例变量?
class Book
attr_accessor :title
def initialize(title)
self.title = title
end
end
Run Code Online (Sandbox Code Playgroud)
本书讨论了"实例变量的属性",并参考了读取实例变量,但它是否也适用于写作?
现在是时候缩短它了:
class Foo
attr_accessor :a, :b, :c, :d, :e
def initialize(a, b, c, d, e)
@a = a
@b = b
@c = c
@d = d
@e = e
end
end
Run Code Online (Sandbox Code Playgroud)
我们有'attr_accessor'来生成getter和setter.
我们有什么要按属性生成初始值设定项吗?
我正在阅读伟大的Michael Hartl教程,在这里构建ruby应用程序.
我试图理解如何创建会话的概念,我坚持理解这一行:
self.current_user = user
Run Code Online (Sandbox Code Playgroud)
在这个方法中:
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
self.current_user = user
end
end
Run Code Online (Sandbox Code Playgroud)
我理解使用user_token创建cookie的整个概念.
但我不明白是什么 self.current_user = user 意思,为什么甚至需要保留这行代码 - 我有令牌的cookie - 为什么我需要知道当前用户?
此外,这个"自我"存储在哪里 - 它不像flash[:success]我在我的一个观点中看到的参数.所以我不明白它在哪里.
在同一模块中也有这两种方法:
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
Run Code Online (Sandbox Code Playgroud)
而且我仍然试图将这个神秘的目的点连接起来current user- 它的目的是创建@current_user在视图中使用的全局变量吗?
如果是这样 - 为什么有这两个重复的功能def current_user=(user)和def current_user
ruby session ruby-on-rails session-variables session-cookies