I have a Rails 3 app with a presenter that lives in lib. The relevant part looks like:
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 is a hack so our presenter can get to helpers; we set it to self in a before_filter. This of course doesn’t work in console, and I want to be able to work with Channel.accessible? in console, so I tried overriding the method like so in .irbrc:
module Channels
class Channel
class << self
puts "in irbrc"
def current_user
User.find(475)
end
end
end
end
And it seems to work when called directly:
ruby-1.9.2-p290 :002 > Channels::Channel.current_user
=> #
But not when called from a channel itself:
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
This is probably either something about the eigenclass vs the class, or something about the timing of loading Channels::Channel. I’ve tried adding a require channels/channel in .irbrc before we reopen the class, but that doesn’t do it… ideas?
In
developmentmode the model classes are defined as temporary copies and re-defined onreload!which can make extensions like this unreliable or ineffective.It’s better to layer this sort of hackery in as some kind of configuration option. For instance:
This way you can start up with any user you’d like: