The Crystal Programming Language Forum

Writing Crystal classes/etc to file

I’m sure I saw a post asking about this.

Basically, for saving objects to files", you need:

  • require "json"
  • include ::JSON::Serializable (or yaml instead; likewise below)
  • def initialize(json_params)...
  • save/load via self.from_json(some_json_string) and self.to_json and save contents of to_json results to file, etc
  • Some things don’t serialize well (e.g.: Symbols), so find alternatives.
  • Performance Note: Writing to file will probably be slower than writing to memory.

See also: Carcin

require "json"

class Foo
  include ::JSON::Serializable # This along with `require "json"` enables `.from_json` and `.to_json` for many classes/structures.
  
    # Symbol don't serialize, but you can use Enum's like:
    enum Widget
      Alpha = 19
      Beta  = 28
      Gamma = 37
    end

    getter bar : Widget

    def initialize(@bar = Widget::Beta)
    # You'll need an initialize that handles all serializable params to be saved/loaded via the json version.
    end
end

# example usage:

foo = Foo.new(bar: Foo::Widget::Gamma)

puts "foo: #{foo}"
puts "foo as json: #{foo.to_json}" # or print to file, etc

foo2 = Foo.from_json(foo.to_json)

puts "foo2: #{foo2}"
puts "foo2.bar: #{foo2.bar}"
puts "foo2.bar as int: #{foo2.bar.to_i}"
puts "foo2.bar's class: #{foo2.bar.class}"
puts "foo2 as json: #{foo2.to_json}"

2 posts were merged into an existing topic: Open, read and write binary into a file