Ruby Private Class Methods
Today I learner that Ruby Module has private_class_method
, this way we can for example make the new
method as private
on service objects:
class MyServiceObject
private_class_method :new
def self.call(*args)
new(*args).call
end
def initialize(foo:)
@foo = foo
end
def call
@foo
end
end
Note that in this example the new
method is private, so the .call
will work, but the .new().call
will raise an error:
irb> MyServiceObject.call(foo: "FOO")
=> "FOO"
irb> MyServiceObject.new(foo: "FOO").call
NoMethodError: private method `new' called for MyServiceObject:Class
Tweet