Frage

I'm trying to override the initialize method. See below

class Restriction < ActiveRecord::Base
  RESTRICTION_TYPES = {
    less_than: "IND<X", 
    greater_than: "X<IND", 
    between: "X<IND<Y"
  }

  def initialize restriction_type_name
    super
    formula = RESTRICTION_TYPES[restriction_type_name]
  end

  private
  def formula=f
    self[:formula] = f
  end

end

When I run r = Restriction.new(:between) I get the exception:

NoMethodError: undefined method `stringify_keys' for :between:Symbol

What am I doing wrong?

BTW I'm doing this due to formula attribute can't be acceded from outside.

War es hilfreich?

Lösung

You can't override initialize, and what you have wouldnt work anyway (it would try to set a local variable called formula in the initialize method). You can, however, move the conditions into your formula= setter, so it reads like:

def formula=(restriction_type_name)
  self[:formula] = RESTRICTION_TYPES[restriction_type_name]
end
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top