如何重构多个模型中出现的方法?
How to refactor method that occurs in multiple models?
我有一个在多个模型中重复的方法。我应该在多个模型中重复这段代码,还是有办法在一个地方包含该方法并使其可用于多个模型?
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
您最好使用 concern
,尽管理论上您也可以使用 superclass
:
这是标准的 Rails 功能:
#app/models/concerns/auth.rb
module Auth
extend ActiveSupport::Concern
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
end
然后你只需要在你的模型中包含 auth
:
#app/models/your_model.rb
class YourModel < ActiveRecord::Base
include Auth
end
超类
另一种方法是创建 "superclass"。
这将是 hacky(因为它用另一个模型填充 ActiveRecord 方法链),但尝试可能会很有趣。
#app/models/auth.rb
class Auth < ActiveRecord::Base
def authenticate?
....
end
end
#app/models/user.rb
class User < Auth
self.table_name = self.model_name.plural
end
老实说,这种方法看起来很老套,尽管它比 concern
更能扩展模型功能。
参考文献:
- table_name
- rails: create scaffold for models to inherit from superclass?
我有一个在多个模型中重复的方法。我应该在多个模型中重复这段代码,还是有办法在一个地方包含该方法并使其可用于多个模型?
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
您最好使用 concern
,尽管理论上您也可以使用 superclass
:
这是标准的 Rails 功能:
#app/models/concerns/auth.rb
module Auth
extend ActiveSupport::Concern
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
end
然后你只需要在你的模型中包含 auth
:
#app/models/your_model.rb
class YourModel < ActiveRecord::Base
include Auth
end
超类
另一种方法是创建 "superclass"。
这将是 hacky(因为它用另一个模型填充 ActiveRecord 方法链),但尝试可能会很有趣。
#app/models/auth.rb
class Auth < ActiveRecord::Base
def authenticate?
....
end
end
#app/models/user.rb
class User < Auth
self.table_name = self.model_name.plural
end
老实说,这种方法看起来很老套,尽管它比 concern
更能扩展模型功能。
参考文献:
- table_name
- rails: create scaffold for models to inherit from superclass?