【问题标题】:Overloading a Rails module's class method in .irbrc在 .irctc 中重载 Rails 模块类方法
【发布时间】: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


    【解决方案1】:

    development 模式下,模型类被定义为临时副本并在reload! 上重新定义,这会使此类扩展变得不可靠或无效。

    最好将这种黑客技术分层作为某种配置选项。例如:

    def current_user
      ENV['USER_ID'] ? User.find(ENV['USER_ID']) : ApplicationController.current_controller.try(:current_or_guest_user)
    end
    

    这样您就可以从任何您喜欢的用户开始:

    USER_ID=475 rails console
    

    【讨论】:

      猜你喜欢
      • 2013-04-30
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2021-03-29
      • 2011-03-22
      • 1970-01-01
      • 2011-01-08
      相关资源
      最近更新 更多