Class: SchemaTools::KlassFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/schema_tools/klass_factory.rb

Class Method Summary collapse

Class Method Details

.build(opts = {}) ⇒ Object

Build classes from schema inside the given namespace. Uses all classes found in schema path: First set a global schema path:

SchemaTools.schema_path = File.expand_path('../fixtures', __FILE__)

Bake classes from all schema.json found

SchemaTools::KlassFactory.build

Go use it

client = Client.new organisation: 'SalesKing'
client.valid?
client.errors.should be_blank


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/schema_tools/klass_factory.rb', line 27

def build(opts={})
  reader = opts[:reader] || SchemaTools::Reader
  schemata = reader.read_all( opts[:path] || SchemaTools.schema_path )
  namespace = opts[:namespace] || Object
  if namespace.is_a?(String) || namespace.is_a?(Symbol)
    namespace = "#{namespace}".constantize
  end
  # bake classes
  schemata.each do |schema|
    klass_name = schema['name'].classify
    next if namespace.const_defined?(klass_name, false)
    klass = namespace.const_set(klass_name, Class.new)
    klass.class_eval do
      include SchemaTools::Modules::Attributes
      include ActiveModel::Conversion
      include SchemaTools::Modules::Validations # +naming + transl + conversion
      has_schema_attrs schema['name'], reader: reader
      validate_with schema['name'], reader:reader
      getter_names = schema['properties'].select{|name,prop| !prop['readonly'] }.keys.map { |name| name.to_sym}
      attr_accessor *getter_names

      def initialize(attributes = {})
        attributes.each do |name, value|
          send("#{name}=", value)
        end
      end

      def persisted?; false end
    end
  end
end