serializable.rb 691 B

12345678910111213141516171819202122232425262728293031323334
  1. # frozen_string_literal: true
  2. module Serializable
  3. extend ActiveSupport::Concern
  4. def initialize(json)
  5. unless json.blank?
  6. json = JSON.parse(json) if json.is_a?(String)
  7. json.to_hash.each do |k, v|
  8. klass = self.class.constants.detect { |c| c.downcase == k.to_sym }
  9. v = self.class.const_get(klass).new(v) if klass
  10. public_send("#{k}=", v)
  11. end
  12. end
  13. end
  14. class_methods do
  15. def load(json)
  16. return nil if json.blank?
  17. new(json)
  18. end
  19. def dump(obj)
  20. # Make sure the type is right.
  21. if obj.is_a?(self)
  22. obj.to_json
  23. else
  24. raise "Expected #{self}, got #{obj.class}"
  25. end
  26. end
  27. end
  28. end