Every example I have found of the setter= syntax is very simple, ie;
def name=(value)
@name = value
end
Can you do something more complex with this syntax? In particular, can you use it without having a corresponding instance variable? Can it be private? Can you do some sort of validation?
I am writing a Rails Controller that can be extended to give basic CRUD functionality to a model that is routed as a resource. It uses a class_attribute to set the name of the Model it will be controlling, and it creates an instance variable based on the name of the Model. It looks something like this;
class ResourceController
class_attribute :model_class_name
def new
resource = self.model_class_name.new
end
protected
def self.init_resource(options={})
self.model_class_name = options[:model_class_name]
end
private
def resource
instance_variable_get(resource_instance_var)
end
def resource=(value)
instance_variable_set(resource_instance_var ,value)
end
def resource_instance_var
"@#{self.resource_class.name.underscore}".to_sym
end
end
With the above code structure I get a NoMethodError
in the View because the View has a Nil instance variable. Using logger.debug
I can trace the stack all the way to resource = ...
, but resource=
is not being called.
If I drop the sugar and useset_resource(value)
everything works fine. Am I asking too much from setter= syntax, or is there some other problem I am missing?