Module: JSONModel

Included in:
ASModel, ArchivesSpaceTypeAttribute, AspaceJsonToManagedContainerMapper, ComponentTransfer, ComponentTransfer, DBAuth, DCModel, InstanceData, Validations, LDAPAuth, MARCModel, METSModel, MODSModel, MODSSerializer, MockAuthenticationSource, NestedRecordResolver, PrintToPDFRunner, RESTHelpers, RelatedAgents, ReportRunner, StreamingImport, SubContainerToAspaceJsonMapper, URIResolver, URIResolver::URIResolver
Defined in:
common/jsonmodel.rb,
common/jsonmodel_client.rb

Defined Under Namespace

Modules: Client, HTTP, Notification, Validations Classes: ValidationException

Constant Summary

@@models =
{}
@@custom_validations =
{}
@@strict_mode =
false
@@error_handlers =
[]

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Object) add_error_handler(&block)



52
53
54
# File 'common/jsonmodel_client.rb', line 52

def self.add_error_handler(&block)
  @@error_handlers << block
end

+ (Object) all(uri, type_descriptor)

Grab an array of JSON objects from ‘uri’ and use the ‘type_descriptor’ property of each object to cast it into a JSONModel.



23
24
25
26
27
# File 'common/jsonmodel_client.rb', line 23

def self.all(uri, type_descriptor)
  JSONModel::HTTP.get_json(uri).map do |obj|
    JSONModel(obj[type_descriptor.to_s]).new(obj)
  end
end

+ (Object) allow_unmapped_enum_value(val, magic_value = 'other_unmapped')



130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'common/jsonmodel.rb', line 130

def self.allow_unmapped_enum_value(val, magic_value = 'other_unmapped')
  if val.is_a? Array
    val.each { |elt| allow_unmapped_enum_value(elt) }
  elsif val.is_a? Hash
    val.each do |k, v|
      if k == 'enum'
        v << magic_value
       else
        allow_unmapped_enum_value(v)
      end
    end
  end
end

+ (Object) backend_url



41
42
43
44
45
46
47
# File 'common/jsonmodel_client.rb', line 41

def self.backend_url
  if Module.const_defined?(:BACKEND_SERVICE_URL)
    BACKEND_SERVICE_URL
  else
    init_args[:url]
  end
end

+ (Boolean) client_mode?

Returns:

  • (Boolean)


301
302
303
# File 'common/jsonmodel.rb', line 301

def self.client_mode?
  @@init_args[:client_mode]
end

+ (Object) custom_validations



18
19
20
# File 'common/jsonmodel.rb', line 18

def self.custom_validations
  @@custom_validations
end

+ (Object) destroy_model(type)



105
106
107
# File 'common/jsonmodel.rb', line 105

def self.destroy_model(type)
  @@models.delete(type.to_s)
end

+ (Object) enum_default_value(name)



296
297
298
# File 'common/jsonmodel.rb', line 296

def self.enum_default_value(name)
  @@init_args[:enum_source].default_value_for(name)
end

+ (Object) enum_values(name)



291
292
293
# File 'common/jsonmodel.rb', line 291

def self.enum_values(name)
  @@init_args[:enum_source].values_for(name)
end

+ (Object) handle_error(err)



56
57
58
59
60
# File 'common/jsonmodel_client.rb', line 56

def self.handle_error(err)
  @@error_handlers.each do |handler|
    handler.call(err)
  end
end

+ (Object) init(opts = {})



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'common/jsonmodel.rb', line 223

def self.init(opts = {})

  @@init_args ||= nil

  # Skip initialisation if this model has already been loaded.
  if @@init_args
    return true
  end

  if opts.has_key?(:strict_mode)
    @@strict_mode = true
  end

  @@init_args = opts

  if !opts.has_key?(:enum_source)
    if opts[:client_mode]
      require_relative 'jsonmodel_client'
      opts[:enum_source] = JSONModel::Client::EnumSource.new
    else
      raise "Required JSONModel.init arg :enum_source was missing"
    end
  end

  # Load all JSON schemas from the schemas subdirectory
  # Create a model class for each one.
  Dir.glob(File.join(File.dirname(__FILE__),
                     "schemas",
                     "*.rb")).sort.each do |schema|
    schema_name = File.basename(schema, ".rb")
    load_schema(schema_name)
  end

  require_relative "validations"

  # For dynamic enums, automatically slot in the 'other_unmapped' string as an allowable value
  if @@init_args[:allow_other_unmapped]
    enum_wrapper = Struct.new(:enum_source).new(@@init_args[:enum_source])

    def enum_wrapper.valid?(name, value)
      value == 'other_unmapped' || enum_source.valid?(name, value)
    end

    def enum_wrapper.editable?(name)
      enum_source.editable?(name)
    end

    def enum_wrapper.values_for(name)
      enum_source.values_for(name) + ['other_unmapped']
    end

    def enum_wrapper.default_value_for(name)
      enum_source.default_value_for(name)
    end

    @@init_args[:enum_source] = enum_wrapper
  end

  true

rescue
  # If anything went wrong we're not initialised.
  @@init_args = nil

  raise $!
end

+ (Object) JSONModel(source)



57
58
59
60
61
62
63
# File 'common/jsonmodel.rb', line 57

def self.JSONModel(source)
  if !@@models.has_key?(source.to_s)
    load_schema(source.to_s)
  end

  @@models[source.to_s] or raise "JSONModel not found for #{source}"
end

+ (Object) load_schema(schema_name)



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'common/jsonmodel.rb', line 145

def self.load_schema(schema_name)
  if not @@models[schema_name]

    old_verbose = $VERBOSE
    $VERBOSE = nil
    src = schema_src(schema_name)

    return if !src

    entry = eval(src)
    $VERBOSE = old_verbose

    parent = entry[:schema]["parent"]
    if parent
      load_schema(parent)

      base = @@models[parent].schema["properties"].clone
      properties = ASUtils.deep_merge(base, entry[:schema]["properties"])

      # Maybe we'll eventually want the version of a schema to be
      # automatically set to max(my_version, parent_version), but for now...
      if entry[:schema]["version"] < @@models[parent].schema_version
        raise ("Can't inherit from a JSON schema whose version is newer than ours " +
               "(our (#{schema_name}) version: #{entry[:schema]['version']}; " +
               "parent (#{parent}) version: #{@@models[parent].schema_version})")
      end

      entry[:schema]["properties"] = properties
    end

    # All records have a lock_version property that we use for optimistic concurrency control.
    entry[:schema]["properties"]["lock_version"] = {"type" => ["integer", "string"], "required" => false}

    # All records must indicate their model type
    entry[:schema]["properties"]["jsonmodel_type"] = {"type" => "string", "ifmissing" => "error"}

    # All records have audit fields
    entry[:schema]["properties"]["created_by"] = {"type" => "string", "readonly" => true}
    entry[:schema]["properties"]["last_modified_by"] = {"type" => "string", "readonly" => true}
    entry[:schema]["properties"]["user_mtime"] = {"type" => "date-time", "readonly" => true}
    entry[:schema]["properties"]["system_mtime"] = {"type" => "date-time", "readonly" => true}
    entry[:schema]["properties"]["create_time"] = {"type" => "date-time", "readonly" => true}

    # Records may include a reference to the repository that contains them
    entry[:schema]["properties"]["repository"] ||= {
      "type" => "object",
      "subtype" => "ref",
      "readonly" => "true",
      "properties" => {
        "ref" => {
          "type" => "JSONModel(:repository) uri",
          "ifmissing" => "error",
          "readonly" => "true"
        },
        "_resolved" => {
          "type" => "object",
          "readonly" => "true"
        }
      }
    }


    if @@init_args[:allow_other_unmapped]
      allow_unmapped_enum_value(entry[:schema]['properties'])
    end

    ASUtils.find_local_directories("schemas/#{schema_name}_ext.rb").
            select {|path| File.exists?(path)}.
            each do |schema_extension|
      entry[:schema]['properties'] = ASUtils.deep_merge(entry[:schema]['properties'],
                                                        eval(File.open(schema_extension).read))
    end

    self.create_model_for(schema_name, entry[:schema])
  end
end

+ (Object) models



77
78
79
# File 'common/jsonmodel.rb', line 77

def self.models
  @@models
end

+ (Object) parse_jsonmodel_ref(ref)



306
307
308
309
310
311
312
# File 'common/jsonmodel.rb', line 306

def self.parse_jsonmodel_ref(ref)
  if ref.is_a? String and ref =~ /JSONModel\(:([a-zA-Z_\-]+)\) (.*)/
    [$1.intern, $2]
  else
    nil
  end
end

+ (Object) parse_reference(reference, opts = {})

Parse a URI reference like /repositories/123/archival_objects/500 into



93
94
95
96
97
98
99
100
101
102
# File 'common/jsonmodel.rb', line 93

def self.parse_reference(reference, opts = {})
  @@models.each do |type, model|
    id = model.id_for(reference, opts, true)
    if id
      return {:id => id, :type => type, :repository => repository_for(reference)}
    end
  end

  nil
end

+ (Object) repository

The currently selected repository (if any)



16
17
18
# File 'common/jsonmodel_client.rb', line 16

def self.repository
  Thread.current[:selected_repo_id]
end

+ (Object) repository_for(reference)



82
83
84
85
86
87
88
# File 'common/jsonmodel.rb', line 82

def self.repository_for(reference)
  if reference =~ /^(\/repositories\/[0-9]+)\//
    return $1
  else
    return nil
  end
end

+ (Object) schema_src(schema_name)



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'common/jsonmodel.rb', line 110

def self.schema_src(schema_name)

  if schema_name.to_s !~ /\A[0-9A-Za-z_-]+\z/
    raise "Invalid schema name: #{schema_name}"
  end

  [*ASUtils.find_local_directories('schemas'),
   File.join(File.dirname(__FILE__), "schemas")].each do |dir|

    schema = File.join(dir, "#{schema_name}.rb")

    if File.exists?(schema)
      return File.open(schema).read
    end
  end

  nil
end

+ (Object) set_repository(id)

Set the repository that subsequent operations will apply to.



10
11
12
# File 'common/jsonmodel_client.rb', line 10

def self.set_repository(id)
  Thread.current[:selected_repo_id] = id
end

+ (Object) strict_mode(val)



22
23
24
# File 'common/jsonmodel.rb', line 22

def self.strict_mode(val)
  @@strict_mode = val
end

+ (Boolean) strict_mode?

Returns:

  • (Boolean)


27
28
29
# File 'common/jsonmodel.rb', line 27

def self.strict_mode?
  @@strict_mode
end

+ (Object) with_repository(id)



30
31
32
33
34
35
36
37
38
# File 'common/jsonmodel_client.rb', line 30

def self.with_repository(id)
  old_repo = Thread.current[:selected_repo_id]
  begin
    self.set_repository(id)
    yield
  ensure
    self.set_repository(old_repo)
  end
end

Instance Method Details

- (Object) JSONModel(source)



66
67
68
# File 'common/jsonmodel.rb', line 66

def JSONModel(source)
  JSONModel.JSONModel(source)
end

- (Object) models

Yield all known JSONModel classes



72
73
74
# File 'common/jsonmodel.rb', line 72

def models
  @@models
end