Tag: 封装

rails中模型属性的保护级别

假设有以下情况 class User < ActiveRecord::Base private def password= p self[:password] = p end def password self[:password] end end 如果有权访问Rails控制台的任何人都可以: Loading development environment (Rails 4.0.0) 2.0.0p247 :001 > User => User(id: integer, name:string, password:string) 2.0.0p247 :002 > u = User.find(1) => # 2.0.0p247 :003 > u.password = “123” NoMethodError: private method ‘password’ called for # 2.0.0p247 […]

Ruby类用静态方法调用私有方法?

我有一个包含许多静态方法的类。 每个人都必须调用一个常用的方法,但我试图不暴露后一种方法。 将其设为私有只允许从类的自己的实例访问? 受保护似乎不会解决这里的问题。 如何隐藏do_calc在静态上下文中被外部调用? (让它可以从前两个静态方法调用。) class Foo def self.bar do_calc() end def self.baz do_calc() end def self.do_calc end end

railsstutorial.org中的SessionsHelper:帮助者应该是视图中不需要的代码的通用模块吗?

railstutorial.org有一个建议让我觉得有点奇怪。 它建议这段代码 : class ApplicationController < ActionController::Base protect_from_forgery include SessionsHelper end include SessionsHelper使得方法可以从ApplicationController ,是的,但它也可以在任何视图中使用它们。 我知道认证/授权是跨领域的,但这真的是最好的地方吗? 在我看来,这似乎可能过于宽泛。 在一个更常见的包含视图帮助程序的模块中放置实现比较重定向的before_filter代码(如railstutorial.org示例所示)似乎令人惊讶。 在视图中不严格需要的function是否可以更好地放在ApplicationController或其他地方? 或者我只是在考虑这个问题?