Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Best idiom for private class methods nowadays, i.e in Ruby >= 2.1 and/or for values of "nowadays" significantly greater than 2014?
# 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 `def self.method` dropped in favor of `class
# <<self; def method`. Note that "private" has additional semantics; all
# methods defined after in in the block will be private, not just
# first_message_in.
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
def self.other_method(message)
# Like this, for example... other_method is public. Would you be misled into
# thinking this method was private, too?
other_implementation_here
end
end
@dbrady

This comment has been minimized.

Copy link
Owner Author

@dbrady dbrady commented Nov 22, 2017

Just realized the misleading bit in option 4 might be countered with an unnecessary backslash, e.g.

private_class_method \
def self.first_message_in(message)
  implementation_here
end

It's syntactically unnecessary and a little bit distracting but I think maybe the distraction admirably serves a purpose: calling direct attention to the fact that "hey, this is ONLY attached to the next line, it does NOT change scope."

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.