Module: Cline::Serializable::ClineData

Defined in:
lib/cline/serializable/cline_data.rb

Overview

Add features to initialize from and save an object to Cline data. Cline data is defined as a JSON file, relative to a base directory. This mixin is intended to be included using the .include_for(self, cline_json_file) method.

Provides:

  • .from_cline_data(base_dir) -> [Object, nil] Provides a new instance initialized from a Cline JSON file present in a base directory.
  • .monitor_cline_data_changes(base_dir, on_change) Provides a monitor to be notified on Cline data changes.
  • #to_cline_data(base_dir) Save an instance in the Cline data.

Requires:

  • .of_hash(hash) -> Object The deserializer that returns an instance from a JSON object.
  • #to_cline_json -> String The serializer that returns a JSON string from the instance.

Defined Under Namespace

Modules: ClassMethods

Public API collapse

Internal collapse

Class Method Details

.include_for(calling_class, cline_json_file_def) ⇒ Object

Include the mixin and configure it with the JSON file path

Parameters:

  • calling_class (Class)

    The class that is calling this method.

  • cline_json_file_def (String, #call)

    The definition of the relative JSON file path to use. Can be one of:

    • [String] The static relative JSON file path to be used.
    • [#call] A proc that can devise dynamically the relative file path from the base directory:
      • Param base_dir [String] The base directory from which the JSON file is searched.
      • Return [String] The corresponding relative JSON file path from base_dir.


109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/cline/serializable/cline_data.rb', line 109

def self.include_for(calling_class, cline_json_file_def)
  calling_class.class_eval do
    include Dir
    include File
    include ClineData

    class << self
      # @return [String] The relative JSON file path
      attr_accessor :cline_json_file_def
    end
  end
  calling_class.cline_json_file_def = cline_json_file_def
end

.included(base) ⇒ Object

Hook used when this mixin is included in a base class

Parameters:

  • base (Class)

    The base class



126
127
128
# File 'lib/cline/serializable/cline_data.rb', line 126

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#saveObject

Save the instance into the Cline data



20
21
22
23
24
25
# File 'lib/cline/serializable/cline_data.rb', line 20

def save
  raise 'This instance has not been initialized from a Cline file' unless file

  FileUtils.mkdir_p(::File.dirname(file))
  ::File.write(file, to_cline_json)
end