Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Which method of declaring a private class method feels most idiomatic now?
# Names of classes and methods have been changed to protect the innocent. Namely
# my sweet, innocent, cherubic, and hopefully continuing, employment.
class MessageTwiddler
# Okay, so: say I want to make a class method private. What's the best idiom
# for doing this in Ruby circa 2017?
# In Ruby 2.0 I can do Options 1 or 2:
# Option 1 - Original Flavor, Most Explicit
def self.first_message_in(message)
implementation_here
end
private_class_method :first_message_in
# Option 2 - Same thing but with class <<self instead of def self.
class <<self
private
def first_message_in(message)
implementation_here
end
end
# Option 3 - In Ruby 2.1, "def" returns the method name as a symbol, so we can
# actually embed the private_class_method call directly. Feels a bit like Java
# or C#, but it is not without its charm.
private_class_method def self.first_message_in(message)
implementation_here
end
# Option 4 - Same as 3 but with private_class_method on its own line. This
# SORTA makes it look we're like saying "private" for the following method,
# which kinda feels nice, but also kinda feels misleading because it is not
# saying "private" for ALL the following methods.
private_class_method
def self.first_message_in(message)
implementation_here
end
# Continuation of option 4... If you didn't recognize private_class_method,
# would you be misled into thinking this method was private, too?
def self.other_method(message)
implementation_here
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.