This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Jan 4th, 2013  |  syntax: None  |  size: 1.16 KB  |  views: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class A
  2.     def initialize(options = {})
  3.         #what goes on in here doesn't really matter for the purpose of this question
  4.         #I just don't want it to be initialized directly
  5.         options.each do |k,v|
  6.             instance_variable_set("@#{k}",v) unless v.nil?
  7.         end
  8.     end
  9. end
  10.  
  11. class B < A
  12.     attr_accessor :class_specific_opt
  13.     def initialize( options = {} )
  14.         @class_specific_opt = "val" unless options[:class_specific_opt].nil?
  15.         super(options)
  16.     end
  17. end
  18.        
  19. class A
  20.   def self.initialize_allowed?
  21.     raise "You cannot initialize instances of this class."
  22.   end
  23.  
  24.   def self.allow_initialize
  25.     class << self
  26.       def initialize_allowed?
  27.         true
  28.       end
  29.     end
  30.   end
  31.  
  32.   def initialize(options = {})
  33.     self.class.initialize_allowed?
  34.     options.each do |k,v|
  35.       instance_variable_set("@#{k}", v)
  36.     end
  37.   end
  38. end
  39.        
  40. class B < A
  41.   allow_initialize
  42. end
  43.  
  44. B.new #=> #<B:0x00000102837d10>
  45.        
  46. class <<A
  47.   undef :new
  48. end
  49.        
  50. A.new #=> NoMethodError: undefined method `new' for A:Class
  51.        
  52. private_class_method :new
  53.        
  54. public_class_method :new
  55.        
  56. class A
  57.   private_class_method :new
  58. end
  59.  
  60. class B < A
  61.   public_class_method :new
  62. end
clone this paste RAW Paste Data