serdes.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. class Dir
  2. def self.mkdir_p(name)
  3. sub = ""
  4. parts = name.split('/').reject { |e| e.empty? }
  5. parts.each do | part |
  6. sub << "/#{part}"
  7. mkdir sub
  8. end
  9. end
  10. end
  11. # Module to help with serialization and deserialization of any type of data
  12. module Serdes
  13. module ClassMethods
  14. def serdes_add_to_register(name)
  15. @serder_register ||= []
  16. @serder_register << name
  17. end
  18. def serdes_reader(name)
  19. serdes_add_to_register(name)
  20. attr_reader(name)
  21. end
  22. def serdes_writer(name)
  23. serdes_add_to_register(name)
  24. attr_writer(name)
  25. end
  26. def serdes_accessor(name)
  27. serdes_add_to_register(name)
  28. attr_accessor(name)
  29. end
  30. def serdes_register()
  31. @serder_register ||= []
  32. return @serder_register
  33. end
  34. end
  35. # include callback, be sure to extend the class with the ClassMethods
  36. def self.included(klass)
  37. klass.extend(ClassMethods)
  38. end
  39. def serdes_dir_name
  40. top = self.class.to_s.gsub('::', '/').downcase
  41. top << '/'
  42. top << self.id.to_s[0]
  43. top << '/'
  44. top << self.id.to_s
  45. return top
  46. end
  47. def serdes_file_name
  48. top = self.id.to_s.dup
  49. top << '.'
  50. top << self.class.to_s.gsub('::', '.').downcase
  51. return top
  52. end
  53. def save
  54. Dir.mkdir_p serdes_dir_name
  55. data = {}
  56. self.class.serdes_register.each do |name|
  57. key = "#{name}"
  58. value = "#{self.send(name.to_sym)}"
  59. data[key] = value
  60. end
  61. full_name = serdes_dir_name + '/' + serdes_file_name
  62. Sitef.save_filename(full_name, [ data ] )
  63. end
  64. end