Reputation: 4478
I have an instance method defined on a class:
class Foo
def is_linux
# some code...
# returns true or false
end
end
And i would like to call this method in a Module:
class Foo
module Dog
is_linux? ? puts "Is Linux" : puts "Is Windows"
end
end
This gives me the following error:
NoMethodError: undefined method `is_linux?' for Foo::Foo:Module
I know i can write
class Foo
module Dog
Foo.new.is_linux? ? puts "Is Linux" : puts "Is Windows"
end
end
But i was wondering if there is a way for the module to access the current instance?
Upvotes: 0
Views: 154
Reputation:
Basically you'll need somehow to "share" your utility methods.
I would suggest to put them into a mixin:
module Mixin
def is_linux?
true
end
end
class Foo
include Mixin # adding methods at instance level
end
class Foo
module Dog
extend Mixin # adding methods at class level
puts is_linux? ? "Is Linux" : "Is Windows"
end
end
#=> Is Linux
Upvotes: 1
Reputation: 23556
There is no such option because subtypes (like module) are not connected with their parents instances. If you need such construct you have can only make is_linux?
class method. If there is no such possibility then propably you have wrong design.
Upvotes: 1