Guest User

Untitled

a guest
Nov 24th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 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 `def self.method` dropped in favor of `class
  17. # <<self; def method`. Note that "private" has additional semantics; all
  18. # methods defined after in in the block will be private, not just
  19. # first_message_in.
  20. class <<self
  21. private
  22. def first_message_in(message)
  23. implementation_here
  24. end
  25. end
  26.  
  27. # Option 3 - In Ruby 2.1, "def" returns the method name as a symbol, so we can
  28. # actually embed the private_class_method call directly. Feels a bit like Java
  29. # or C#, but it is not without its charm.
  30. private_class_method def self.first_message_in(message)
  31. implementation_here
  32. end
  33.  
  34. # Option 4 - Same as 3 but with private_class_method on its own line. This
  35. # SORTA makes it look we're like saying "private" for the following method,
  36. # which kinda feels nice, but also kinda feels misleading because it is not
  37. # saying "private" for ALL the following methods.
  38. private_class_method
  39. def self.first_message_in(message)
  40. implementation_here
  41. end
  42.  
  43. def self.other_method(message)
  44. # Like this, for example... other_method is public. Would you be misled into
  45. # thinking this method was private, too?
  46. other_implementation_here
  47. end
  48. end
Add Comment
Please, Sign In to add comment