0

Suppose I have this

module Command
    extend ActiveSupport::Concern

      included do
        @path ||= File.join("#{file_path}", "some_file")
      end

      def file_path
        File.expand_path("some_other_file")
      end
...

When the module is included, I get undefined local variable or method file_path. So is there a way, to make the file_path method be recognized when the module is included ? (of course without putting file_path in the included method)

1
  • Module#included didn't take block.. Where you found the code ? Commented Nov 4, 2013 at 10:40

2 Answers 2

1

You are calling the method file_path,in the method included, do..end block. That means with scope is set as Command class. But file_path is the instance_method,so Command.file_path is throwing an legitimate error. You have to call the method file_path,on the instance of the class which is including the Command module. One example to illustrate this -

module A
    def self.included(mod)
        p foo
    end
    def foo
        2
    end
end

class B
    include A
end

# `included': undefined local variable or method `foo' for A:Module (NameError)

The error is coming because inside the method included self is A. A has no class method named as foo,so the error comes out. Now to fix it we should call it as below:

module A
    def self.included(mod)
        p mod.new.foo
    end
    def foo
        2
    end
end

class B
    include A
end

# >> 2
Sign up to request clarification or add additional context in comments.

2 Comments

ok thanks interesting ! but should I prefer the response of @newben. because module Command is included inside some class Generator < Initializer, where Initializer has an initialize(param1,param2) method. So following your method I get a legitimate ` wrong number of arguments (0 for 2)`... ?
@user1611830 Whichever fits good to you.. Because I don't know internal code you are having. I just gave you hints,how to move ahead.
1

You can try this :

module Command extend ActiveSupport::Concern

  def self.extended(klass)
    @path ||= File.join("#{klass.file_path}", "some_file")
  end

  def file_path
    File.expand_path("some_other_file")
  end

and then extend your module where you call it !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.