Class: SchemaTools::KlassFactory
- Inherits:
-
Object
- Object
- SchemaTools::KlassFactory
- Defined in:
- lib/schema_tools/klass_factory.rb
Class Method Summary collapse
-
.build(opts = {}) ⇒ Object
Build ruby classes from a schema with getter/setter methods for all properties and validation.
- .build_class(schema, namespace, reader) ⇒ Object
- .namespace(name) ⇒ Object
Class Method Details
.build(opts = {}) ⇒ Object
Build ruby classes from a schema with getter/setter methods for all properties and validation. Uses all classes(json files) found in global schema path or you can add a custom path. A namespace can be given under which the classes will be created. First set a(global) schema path:
SchemaTools.schema_path = File.('../fixtures', __FILE__)
Build classes from all json files in schema path
SchemaTools::KlassFactory.build
Go use them
client = Client.new organisation: 'SalesKing'
client.valid?
client.errors.should be_blank
With custom options:
SchemaTools::KlassFactory.build namespace: MyModule,
path: 'custom/path/to_json_schema'
31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/schema_tools/klass_factory.rb', line 31 def build(opts={}) reader = opts[:reader] || SchemaTools::Reader schemata = reader.read_all( opts[:path] || SchemaTools.schema_path ) namespace = opts[:namespace] || Object namespace = "#{namespace}".constantize if namespace.is_a?(String) || namespace.is_a?(Symbol) # bake classes schemata.each do |schema| next if !schema['name'] or namespace.const_defined?(schema['name'].classify, false) build_class(schema, namespace, reader) end end |
.build_class(schema, namespace, reader) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/schema_tools/klass_factory.rb', line 46 def build_class(schema, namespace, reader) klass_name = schema['name'].classify 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| public_send("#{name}=", value) end end def persisted?; false end end # class end |
.namespace(name) ⇒ Object
70 71 72 |
# File 'lib/schema_tools/klass_factory.rb', line 70 def namespace(name) end |