refeniz
refeniz

Reputation: 595

RAILS: Accessing the current controller from inside a lib class

In my controller I have:

@list = ListView.new()

The template contains:

= @list.render

And in lib/list_view.rb I have:

class ListView

    def render
        controller_name.inspect
    end

end

When I run this code I get a undefined local variable or method 'controller_name' error. I'm still new to Rails but I'm sure there's a way to do this as will_paginate does it here: https://github.com/mislav/will_paginate/blob/master/lib/will_paginate/view_helpers/action_view.rb#L92

It does appear that will_paginate might be a module and not a class? I'm missing something...

Upvotes: 0

Views: 282

Answers (1)

jvillian
jvillian

Reputation: 20263

You probably want to do something like:

class ListView

    def initialize(controller)
      @controller = controller
    end

    def render
      controller_name.inspect
    end

  private 

    def controller()   @controller    end

    def controller_name
      controller.controller_name
    end

end

Then in your controller, do:

@list = ListView.new(self)

I'm guessing that you're going for the presenter pattern. If so, you'll want to watch Ryan Bates great RailsCast on the subject where you'll learn how to get your presenter to actually render something.

Upvotes: 1

Related Questions