Reputation: 4857
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)
Upvotes: 0
Views: 249
Reputation: 118261
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
Upvotes: 1
Reputation: 11609
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 !
Upvotes: 1