Search code examples
rubyrake

How to call an class's included module function from a rake?


I am in a task in a rake file.

# gottaRunThis.rake
task [:var] => :environment do |t, args|

    Foo::Bar::Bell::this_function(args.var)
    #runs Bell::this_function(var) but fails to complete.
    # errors out with the words:
    # NoMethodError: undefined method `put' for nil:NilClass
    # Because Bell needs a @connection variable that doesn't exist in
    # it's context when called directly.
end

The thing is, the target module and def are meant to be included in another class.

# mainclass.rb
module Foo
  module Bar
    class TheMainClass
      include Foo::Bar::Bell
      def initialize
        @site = A_STATIC_SITE_VARIABLE
        @connection = self.connection
      end
      def connection
        # Connection info here, too verbose to type up
      end
    end
  end
end

And Bell looks like.

# bell.rb
module Foo
  module Bar
    module Bell
    def do_the_thing(var)
      #things happen here
      #var converted to something here
      response = @connection.put "/some/restful/interface, var_converted
    end
  end
end

Should I modify Bell so it somehow is including TheMainClass? (And if so, I don't know how?) Or is there some syntax I should use in my rake file like

Foo::Bar::TheMainClass::Bell::do_the_thing(args.var)
#I don't think this works... should it? What would the equivilent but working version look like?

Solution

  • Included methods are available as instance methods, so you can call do_the_thing like this:

    main_class = Foo::Bar::TheMainClass.new
    main_class.do_the_thing(args.var)