1
module AHelper
   class Builder
     def link
       build_link(@apple)
     end
   end
   def build_link(sth)
     link_to "#", "buy #{sth}"
   end
end

In a helper module, link_to method is available to be invoked but inside the class Builder, it isn't. So I'm looking a way to call external method included in a helper module and passing a instance variable value to this method.

I don't want to include ActionView::UrlHelper into the class as it is already available to the helper module. And link_to is just an example case to demo the needs here. How to do this in ruby on rails?

canoe
  • 1,273
  • 13
  • 29
  • Possible duplicate of [Can Rails Routing Helpers (i.e. mymodel\_path(model)) be Used in Models?](http://stackoverflow.com/questions/341143/can-rails-routing-helpers-i-e-mymodel-pathmodel-be-used-in-models) – lcguida Mar 29 '16 at 07:20
  • Not duplicate since `link_to` is only an example in this question. – Albin Mar 29 '16 at 09:31

1 Answers1

3

You can achieve this by passing the view context to the instance of Builder

module AHelper
    class Builder
      def initialize(view)
        @view = view
      end
      def link
        @view.build_link(@apple)
      end
    end
    def build_link(sth)
      link_to "#", "buy #{sth}"
    end
end

And when you instantiate the builder you pass in view_context if it is in a controller or self if it is in a helper or view.

Albin
  • 2,912
  • 1
  • 21
  • 31