Friday, 9 August 2013

Call private class method from private instance method

Call private class method from private instance method

I am new to Ruby and came from C# world. In C# it is legal to do stuff
like this:
public class Test
{
public void Method()
{
PrivateMethod();
}
private void PrivateMethod()
{
PrivateStaticMethod();
}
private static void PrivateStaticMethod()
{
}
}
Is it possible to do something similar in Ruby?
A little bit of context: I have a Rails app... One of the models has a
private method that sets up some dependencies. There is a class method
that creates initialized instance of the model. For legacy reasons there
are some instances of the model that are not initialized correctly. I
added an instance method that initializes 'uninitialized' instances where
I want to do same initialization logic. Is there a way to avoid
duplication?
Sample:
class MyModel < ActiveRecord::Base
def self.create_instance
model = MyModel.new
model.init_some_dependencies # this fails
model
end
def initialize_instance
// do some other work
other_init
// call private method
init_some_dependencies
end
private
def init_some_dependencies
end
end
I tried to convert my private method to a private class method, but I
still get an error:
class MyModel < ActiveRecord::Base
def self.create_instance
model = MyModel.new
MyModel.init_some_dependencies_class(model)
model
end
def initialize_instance
# do some other work
other_init
# call private method
init_some_dependencies
end
private
def init_some_dependencies
MyModel.init_some_dependencies_class(self) # now this fails with
exception
end
def self.init_some_dependencies_class(model)
# do something with model
end
private_class_method :init_some_dependencies_class
end

No comments:

Post a Comment