Saving dynamic Ruby classes

I have a question of curiosity. If I have a ruby ​​class, then I dynamically add class methods, class variables, etc. to it. At runtime, do I care to save the changed class definition so that the next time I run the application I can use it again?

+5
source share
5 answers

Just sorting an object (as others have said) will not work. Let's look at an example. Consider this class:

class Extras
  attr_accessor :contents
  def test
    puts "This instance of Extras is OK. Contents is: " + @contents.to_s
  end

  def add_method( name )
    self.class.send :define_method, name.to_sym do
      puts "Called " + name.to_s
    end
  end
end

Now let's write a program that creates an instance, adds a method to it and saves it to disk:

require 'extras'

fresh = Extras.new
fresh.contents = 314
fresh.test # outputs "This instance of Extras is OK. Contents is: 314"
fresh.add_method( :foo )
fresh.foo # outputs "Called foo"

serial = Marshal.dump( fresh )
file = File.new "dumpedExample", 'w'
file.write serial

, "test" "foo". , , , , :

require 'extras'

file = File.new 'dumpedExample', 'r'
serial = file.read

reheated = Marshal.load( serial )
reheated.test # outputs "This instance of Extras is OK. Contents is 314"
reheated.foo # throws a NoMethodError exception 

, , , ( -) , .

, , , . , , , , .

, -. included -, .

+1

. . - , , . , make_special_method(purpose, value), , , , , .

+4

, , .

, , :

class String
  def rot13
    return self.tr('a-z', 'n-za-m')
  end
end

rot13 String. , # rot13. , , , rot13, , , . rot13 - () . !

, , , , :

class String
  @@number_of_tr_calls_made = 0
  # Fix up #tr so that it increments @@number_of_tr_calls_made
end

, @@number_of_tr_calls_made, , Ruby: . !

- , , , - :

greeting = "Hello"
class <<greeting
  def rot13
    return self.tr('a-z', 'n-za-m')
  end
end
encrypted_greeting = greeting.rot13

, . rot13. , "". Ruby , Singleton String, rot13 .

, ( , , , , Marshal.load Singleton). , , , . :

class HighlySecurableString < String
  def rot13
    return self.tr('a-z', 'n-za-m')
  end
end
greeting = HighlySecurableString.new("hello")
+2

, ? Marshal, .

-1

All Articles