Module: JsonSchema::Attributes::ClassMethods

Defined in:
lib/json_schema/attributes.rb

Overview

Provides class-level methods for the Attributes module.

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#copyable_attrsObject (readonly)

Attributes that should be copied between classes when invoking Attributes#copy_from.

Hash contains instance variable names mapped to a default value for the field.



13
14
15
# File 'lib/json_schema/attributes.rb', line 13

def copyable_attrs
  @copyable_attrs
end

#schema_attrsObject (readonly)

Attributes that are part of the JSON schema and hyper-schema specifications. These are allowed to be accessed with the [] operator.

Hash contains the access key mapped to the name of the method that should be invoked to retrieve a value. For example, ‘type` maps to `type` and `additionalItems` maps to `additional_items`.



21
22
23
# File 'lib/json_schema/attributes.rb', line 21

def schema_attrs
  @schema_attrs
end

Instance Method Details

#attr_copyable(attr, options = {}) ⇒ Object

identical to attr_accessible, but allows us to copy in values from a target schema to help preserve our hierarchy during reference expansion



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/json_schema/attributes.rb', line 25

def attr_copyable(attr, options = {})
  attr_accessor(attr)

  ref = :"@#{attr}"
  # Usually the default being assigned here is nil.
  self.copyable_attrs[ref] = options[:default]

  if default = options[:default]
    # remove the reader already created by attr_accessor
    remove_method(attr)

    need_dup = [Array, Hash, Set].include?(default.class)
    define_method(attr) do
      val = instance_variable_get(ref)
      if !val.nil?
        val
      else
        need_dup ? default.class.new : default
      end
    end
  end
end

#attr_schema(attr, options = {}) ⇒ Object



48
49
50
51
# File 'lib/json_schema/attributes.rb', line 48

def attr_schema(attr, options = {})
  attr_copyable(attr, :default => options[:default])
  self.schema_attrs[options[:schema_name] || attr] = attr
end

#inherit_attrsObject

Directive indicating that attributes should be inherited from a parent class.

Must appear as first statement in class that mixes in (or whose parent mixes in) the Attributes module.



58
59
60
61
# File 'lib/json_schema/attributes.rb', line 58

def inherit_attrs
  @copyable_attrs = self.superclass.instance_variable_get(:@copyable_attrs).dup
  @schema_attrs = self.superclass.instance_variable_get(:@schema_attrs).dup
end

#initialize_attrsObject

Initializes some class instance variables required to make other methods in the Attributes module work. Run automatically when the module is mixed into another class.



66
67
68
69
# File 'lib/json_schema/attributes.rb', line 66

def initialize_attrs
  @copyable_attrs = {}
  @schema_attrs = {}
end