Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Add Comment
Please, Sign In to add comment