Csteele5
Csteele5

Reputation: 1292

Ruby subclass not inheriting parent method or not able to call parent methods in class body

I'm making a page-object.

require 'watir-webdriver'

class Page

  attr_accessor :driver

  def initialize
    @driver = Watir::Browser.new :phantomjs
    @driver.goto(some_arbitrary_url)
  end

  def element(**attrs)
    @driver.element( id: attrs[:id], tag_name: attrs[:tag_name])
  end

  def elements(**attrs)
    @driver.elements( class: attrs[:class], tag_name: attrs[:tag_name])
  end

end

However when I subclass the Page class, I cannot use it's element methods in the class body, unless I put them in a method, like so:

class Home < Page

  #throws NoMethodError: undefined method 'element' for Home:Class
  some_element = element(id: 'elements_id')

  #works
  def some_arbitrary_element
    element(id: 'elements_id')
  end

end

So far, just tinkering, I've tried doing protected: element, elements as well as self.element(...) both to no avail. So what's going on? I'm not reading anything enlightening in Matz' Ruby book about method inheritance, and usually Ruby is so unsurprising, so it's hard for me to identify where the problem actually is.

Upvotes: 3

Views: 2272

Answers (1)

Stewart
Stewart

Reputation: 3161

You're calling element as if it was defined as a class method. Any code that is in a class definition but not in a method definition will only be able to call class methods. One way to make the method visible from where your calling it would be to change the signature so it becomes a method of the class object.

class Page
  def self.element
  end
end

Upvotes: 1

Related Questions