2011-09-29 2 views
0

lib에있는 발표자가있는 레일 3 앱이 있습니다. 우리의 발표자가 도우미를 얻을 수 있도록.irbrc에서 Rails 모듈의 클래스 메소드 오버로드

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가 해킹;

lib/channels/channel.rb : 같은 관련 부분이 보인다 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 

를 직접 호출하면 작동하는 것 같다 :

루비 1.9.2-p290 : 002> 채널 :: 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 

이것은 CL 대 eigenclass에 대한 하나 뭔가 아마 엉덩이, 또는 채널로드 시간에 대한 무언가 : : 채널. 나는 우리가 클래스를 다시 열기 전에 .irbrc에 require channels/channel을 추가하려고 시도했으나 아이디어를 얻지 못했습니까?

답변

0

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