Hi --

On Sat, 3 Feb 2007, Francois Beausoleil wrote:

> Hi all !
>
> I'm on Rails, and I have a general Ruby question.  Here's a part of my code:
>
> class MockControllerBase; end
>
> module AuthenticatedSystem
> def self.included(base)
>   base.send :include, AuthenticatedSystem::InstanceMethods
>
>   base.send :extend, AuthenticatedSystem::ClassMethods
> end
>
> module ClassMethods
>   def required_permissions(options={})
>     logger.debug
> {"AuthenticatedSystem#required_permissions(#{options.inspect})"}
>   end
> end
>
> module InstanceMethods
>   def authorized?
>     false
>   end
> end
> end
>
> class AuthenticatedSystemAuthorizationTest < Test::Unit::TestCase
> def setup
>   class << @controller = MockControllerBase.new
>     include AuthenticatedSystem
>   end
> end
>
> def test_wide_open_lets_any_action_go_through
>   @controller.class.required_permissions true
>
>   @params[:action] = "create"
>   assert @controller.authorized?
> end
> end
>
> I cannot seem to call #required_permissions after it was included.
> How should I access it ?
>
> Both
> @controller.class.required_permissions true
>
> and
> @controller.required_permissions true
>
> raise a NoMethodError, with a different object.

You've included the module in the singleton class of @controller,
which is neither @controller nor @controller.class.  So
required_permissions is a method of what would be
@controller.singleton_class if this method existed:

   class Object
     def singleton_class
       class << self
         self
       end
     end
   end

:-)

> Should I refactor, or do things differently ?

I would do it differently, because I've never been a fan of the
InstanceMethods/ClassMethods thing.  I prefer just to include or
extend separate modules as needed and where needed.  But I know it's
very popular.


David

-- 
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
    (See what readers are saying!  http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)