定义了一个 class 的扩展 moudle(BaseModel),但是在生产环境下不走这个方法。是不是我要在初始化应用程序的时候引入?具体怎么做? 代码如下:
module BaseModel extend ActiveSupport::Concern mattr_accessor :current_user included do |base| p "#{base}" #走不进这个方法,求解。 end end
included {|base| dont_do_this if Rails.env.production? }
但是区分环境的代码是很丑的,最好是不写,一定要写的话能把开关放在 config/produciton 里面会稍好。实在要写在这里也需要怀着痛恨的心情和内疚的表情 :D
#1 楼 @billy 把代码写入 produciton.rb 中?
怎么 include 的?
#3 楼 @rei class model include BaseModel end 就这样引入的
#4 楼 @yqwoe 写在哪里,放在哪里?
#5 楼 @rei BaseModule class 都是放在 models 文件夹下的
#5 楼 @rei 不好意思,刚才太匆忙了,没完整的描述出来。我定义了一个 module BaseModel Current_user Inculded |base| P @@current_user End End
我在 applicationctroller 中定义了一个 before_action {BaseModel·current_user=current_user}
Class model Include BaseModel End
访问得不到 current_user
太多问题了。current_user 不能作为 class variable 或者 class attribute, 否则你的 current_user 永远只有一个。另外 Controller 和 Model 的职责也含混不清。建议楼主先把逻辑想清楚再说。区分环境是小事。
#8 楼 @billy 我的逻辑是我每次请求 controller 就要判断当前用户是否有某个数据库访问权限,所以需要在 controller 和 module 之间传递当前登录的 User 对象。然后根据 User 中得某个字段来判断是否有权限。我的判断是写在钩子方法中得。
@yqwoe module 不是独立的东西,你要把它想成 Controller 或者 Model 的一部分。这个事情是 Controller 的职责,不是 Model 的。do_this if current_user.is_admin?。你可以写成 Controller 的 Mixin, 默认 current_user 方法已经存在。另外不可以用 mattr_accessor 也不可以用@@, 这些都是进程不安全的。
do_this if current_user.is_admin?
#10 楼 @billy 能单独请教一下你吗?我的邮箱是 [email protected],多谢了。
@yqwoe
请教问题时,请正确排版你的代码。
```ruby module BaseModel ... end ```
https://help.github.com/articles/github-flavored-markdown/#syntax-highlighting