5

I want to invoke method a from method of module B. How can I do it? I don't want to specify A::a every time.

module A
  def self.a
    "a"
  end
end

module B
  extend A

  def self.b
    a
  end
end

p B::b  # => undefined local variable or method `a' for B:Module
5
  • 1
    You're extending A, but a is a class method on A if you had def a and not def self.a it would work as expected, otherwise use include instead of extend Commented Jan 4, 2013 at 14:27
  • Do you need really need A::a to be a class method? Commented Jan 4, 2013 at 14:27
  • @DaveNewton I think, yes Commented Jan 4, 2013 at 14:47
  • @AndreyBotalov If it doesn't, then use the normal extends mechanism as in quandary's answer. Commented Jan 4, 2013 at 15:21
  • @DaveNewton I meant A::a should be module method. sorry Commented Jan 4, 2013 at 16:00

3 Answers 3

7

When using extend or include, Ruby will only mixin the instance methods. Extend will mix them in as class methods, but it won't mix in the class methods. Therefore, an easy solution to your query:

module A
  def a  ## Change to instance
    "a"
  end
end

module B
  extend A

  def self.b
    a
  end
end

p B::b #=> "a"
p B.b  #=> "a"
Sign up to request clarification or add additional context in comments.

Comments

3

I found here a method to solve it but it doesn't look good to me:

module A 
  module ClassMethods
    def a
      puts "a"
    end
  end
  extend ClassMethods
  def self.included( other )
    other.extend( ClassMethods )
  end
end

module B
  include A

  def self.b
    a
  end
end

p B::b  # => "a"

Comments

0

You could try this "weird" code:

module A
  def self.a
    "a"
  end
end

module B
  extend A

  def self.method_missing(name, *args)
    if name =~ /a/
        A::a *args
    else
        raise "MethodMissed: #{name}"
    end
  end

  def self.b
    a
  end
end

p B::b

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.