lifecoder
lifecoder

Reputation: 1434

How to access class setter in easy way?

How it is possible to easy access setter within a same class?

Lets say I have this call:

# some_file.rb , create a new object
temperature = Measurement.new 'temperature', 36.6

And a model:

# Measurements.rb , some model
class Measurement
  attr_accessor :value, :type
  attr_reader :device, :title, :label

  def initialize type, value
    # This one works, but not trigger the setter
    @type = type
    # And this one trigger setter
    self.type = type
  end

  def type= new_type
    # do something very important
  end    
end

Does this mean i always need to use self.var = instead of @var = if I ever want to use setters with this variable without renaming it everywhere in the class? Are there any more difference, and some better way to add a setter?

Upvotes: 2

Views: 54

Answers (1)

Linuxios
Linuxios

Reputation: 35793

Yes, you always do. In Ruby, there is not such thing really as a setter. Just a method that ends in =. However, because of syntax ambiguity you must always preface setters with an object and a period, as otherwise Ruby will see an assignment to a local variable instead.

In other words, remember that @blah is raw access, and will never trigger a method (not completely true, there are some logging and debugging hock methods, but never-mind).

So just live with self.blah= if your setter is that important.

Upvotes: 2

Related Questions