Overriding a method with a getter in Ruby

Viewed 231

The code below runs as intended however are they any disadvantages to override a method (see action_label in the code below) with the getter of an attribute? See the :action_label in the code

class BaseAction
  def action_label
    raise NotImplementedError
  end

  def run
    puts "Running action: #{action_label}"
    yield        
  end
end

class SimpleAction < BaseAction  

  def initialize(label)    
    @action_label = label
  end

  private
  attr_reader :action_label
end

sa = SimpleAction.new("foo")
sa.run {puts "action!"}
1 Answers

attr_reader :action_label is just defining a method. "getters" in Ruby are just methods like this

def action_label
  @action_label
end

attr_reader is shorthand for defining such a method.

There is nothing wrong with redefining a method in a subclass, that's one of the big features of OOP.

Also that is not what NotImplementedError is for. Raise something else.

Related