module Hashie::Extensions::Persistable::ClassMethods
@example Add a YAML loader by including Persistable
class Settings < Hash include Hashie::Extensions::MergeInitializer include Hashie::Extensions::Persistable end file = Tempfile.new(['hashie-example', '.yaml'], Dir.pwd) begin file.write("---\ntheme: dark\n") file.flush Settings.load(file.path) # => { 'theme' => 'dark' } ensure file.close! end
Public Instance Methods
load(path)
click to toggle source
@example Load safe YAML data and remember its path
class Settings < Hash include Hashie::Extensions::MergeInitializer include Hashie::Extensions::Persistable end file = Tempfile.new(['hashie-example', '.yaml'], Dir.pwd) begin file.write("---\ntheme: dark\n") file.flush settings = Settings.load(file.path) settings['theme'] # => 'dark' settings.persistable_path # => File.expand_path(file.path) ensure file.close! end
# File lib/hashie/extensions/persistable.rb, line 57 def load(path) path = File.expand_path(File.path(path)) data = Psych.safe_load(File.read(path), permitted_classes: [Symbol], aliases: false) raise TypeError, 'persisted YAML must contain a hash' unless data.is_a?(::Hash) new(data).tap { |object| object.instance_variable_set(:@persistable_path, path) } end