lib/syncano/resources.rb in syncano-4.0.0.alpha1 vs lib/syncano/resources.rb in syncano-4.0.0.alpha2

- old
+ new

@@ -1,28 +1,59 @@ require 'dirty_hashy' module Syncano module Resources class << self + def build_definitions(schema_definition) + schema_definition.map do |name, raw_resource_definition| + ::Syncano::Schema::ResourceDefinition.new(name, raw_resource_definition) + end + end + def define_resource_class(resource_definition) - const_set resource_definition.name, new_resource_class(resource_definition) + resource_class = new_resource_class(resource_definition) + + const_set resource_definition.name, resource_class + + if resource_definition[:collection] + resources_paths.collections.define resource_definition[:collection][:path], resource_class + end + + if resource_definition[:member] + resources_paths.members.define resource_definition[:member][:path], resource_class + end + + resource_class end + def resources_paths + ::Syncano::Resources::Paths.instance + end + def new_resource_class(definition) attributes_definitions = definition.attributes ::Class.new(::Syncano::Resources::Base) do self.create_writable_attributes = [] self.update_writable_attributes = [] attributes_definitions.each do |attribute_definition| + attribute attribute_definition.name, type: attribute_definition.type, - default: attribute_definition.default, - force_default: attribute_definition.force_default? + default: attribute_definition.default - if attribute_definition.required? + # TODO extract to a dynamically defined module + define_method("#{attribute_definition.name}=") do |new_value| + if new_value != read_attribute(attribute_definition.name) + send("#{attribute_definition.name}_will_change!") + end + + super new_value + end + + if attribute_definition.validate? validates attribute_definition.name, presence: true end validates attribute_definition.name, length: attribute_definition.required_length @@ -98,21 +129,22 @@ end end end (definition[:associations]['links'] || []).each do |association_schema| - if association_schema['type'] == 'list' - define_method(association_schema['name']) do - has_many_association(association_schema['name']) - end - elsif association_schema['type'] == 'detail' && association_schema['name'] != 'self' - define_method(association_schema['name']) do - belongs_to_association(association_schema['name']) - end - elsif association_schema['type'] == 'run' - define_method(association_schema['name']) do |config = nil| - custom_method association_schema['name'], config - end + case association_schema['type'] + when 'list' + define_method(association_schema['name']) do + has_many_association(association_schema['name']) + end + when 'run' + define_method(association_schema['name']) do |config = nil| + custom_method association_schema['name'], config + end + when 'poll' + define_method(association_schema['name']) do |config = nil| + async_method association_schema['name'], config + end end end private \ No newline at end of file