Benjineer
Benjineer

Reputation: 1680

Ruby mixin class methods

I'm attempting to provide a class attribute setter and getter via a mixin, but clearly I'm doing something fundamentally wrong.

This code results in the error mod.rb:16:in '<class:Klass>': undefined method 'set_n' for Klass:Class (NoMethodError):

module Mixin
  @@n = 0

  def self.set_n(n)
    @@n = n
  end

  def self.get_n
    @@n
  end
end


class Klass
  include Mixin
  set_n 100
end


n = Klass.get_n

Little help?

Upvotes: 0

Views: 235

Answers (2)

Stefan
Stefan

Reputation: 114158

I'd rewrite the module using instance methods and instance variables, i.e.:

module Mixin
  def set_n(n)
    @n = n
  end

  def get_n
    @n ||= 0
  end
end

The above can then be added to your class via extend:

class Klass
  extend Mixin

  set_n 100
end

Klass.get_n #=> 100

Note that get_ and set_ prefixes are quite unidiomatic in Ruby. You typically use the attribute's name as the getter and append a = for the setter.

Upvotes: 1

Benjineer
Benjineer

Reputation: 1680

As @Cary Swoveland mentioned, module methods can't be mixed in so I'll need to implement a base class:

class BaseClass
  @@n = 0

  def self.set_n(n)
    @@n = n
  end

  def self.get_n
    @@n
  end
end


class Klass < BaseClass
  set_n 100
end


n = Klass.get_n

This works as intended, but I won't be able to use it in a multiple inheritance scenario (hopefully won't be required).

Upvotes: 0

Related Questions