【发布时间】:2011-09-29 14:59:31
【问题描述】:
我有一个 Rails 3 应用程序,其演示者居住在 lib。相关部分如下所示:
lib/channels/channel.rb:
module Channels
class Channel
def current_user
ApplicationController.current_controller.try(:current_or_guest_user)
end
def self.find_by_key(key)
@@channels.find { |c| c.key == key.to_sym }
end
private
def self.class_initialize
@@channels = []
Dir.glob("#{Rails.root}/lib/channels/channel_defs/*.rb").each do |f|
require_dependency f
@@channels << "Channels::#{File.basename(f, '.rb').camelize}".constantize.new
end
end
class_initialize
end
end
lib/channels/channel_defs/activity.rb
module Channels
class Activity
def current_user
ApplicationController.current_controller.try(:current_or_guest_user)
end
def accessible?
current_user.registered_user?
end
end
end
ApplicationController.current_controller 是一个 hack,因此我们的演示者可以找到帮助者;我们在 before_filter 中将其设置为self。这当然在控制台中不起作用,我希望能够使用 Channel.accessible?在控制台中,所以我尝试在.irbrc 中覆盖这样的方法:
module Channels
class Channel
class << self
puts "in irbrc"
def current_user
User.find(475)
end
end
end
end
而且直接调用好像也可以:
ruby-1.9.2-p290:002 > Channels::Channel.current_user => #
但不是从频道本身调用时:
Channels::Channel.find_by_key(:activity).accessible?NoMethodError: undefined method `registered_user?' for nil:NilClass
from /Users/jay/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.0.9/lib/active_support/whiny_nil.rb:48:in `method_missing'
from /Users/jay/src/tiptap/2t2/lib/channels/channel_defs/activity.rb:16:in `accessible?'
from (irb):1
这可能与 eigenclass 与类有关,或者与加载 Channels::Channel 的时间有关。在我们重新开课之前,我尝试在 .irbrc 中添加require channels/channel,但这并没有做到……有什么想法吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 console autoload irb