Guest User

Untitled

a guest
Nov 24th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. # Names of classes and methods have been changed to protect the innocent. Namely
  2. # my sweet, innocent, cherubic, and hopefully continuing, employment.
  3. class MessageTwiddler
  4.  
  5. # Okay, so: say I want to make a class method private. What's the best idiom
  6. # for doing this in Ruby circa 2017?
  7.  
  8. # In Ruby 2.0 I can do Options 1 or 2:
  9.  
  10. # Option 1 - Original Flavor, Most Explicit
  11. def self.first_message_in(message)
  12. implementation_here
  13. end
  14. private_class_method :first_message_in
  15.  
  16. # Option 2 - Same thing but with class <<self instead of def self.
  17. class <<self
  18. private
  19. def first_message_in(message)
  20. implementation_here
  21. end
  22. end
  23.  
  24. # Option 3 - In Ruby 2.1, "def" returns the method name as a symbol, so we can
  25. # actually embed the private_class_method call directly. Feels a bit like Java
  26. # or C#, but it is not without its charm.
  27. private_class_method def self.first_message_in(message)
  28. implementation_here
  29. end
  30.  
  31. # Option 4 - Same as 3 but with private_class_method on its own line. This
  32. # SORTA makes it look we're like saying "private" for the following method,
  33. # which kinda feels nice, but also kinda feels misleading because it is not
  34. # saying "private" for ALL the following methods.
  35. private_class_method
  36. def self.first_message_in(message)
  37. implementation_here
  38. end
  39.  
  40. # Continuation of option 4... If you didn't recognize private_class_method,
  41. # would you be misled into thinking this method was private, too?
  42. def self.other_method(message)
  43. implementation_here
  44. end
  45. end
Add Comment
Please, Sign In to add comment