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.
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# 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 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 |