Sha256: 4011954cdead443b379cacfd76be2bbb75a3a8b68c94b6bbe33cbc72c0e3606d

Contents?: true

Size: 1.77 KB

Versions: 9

Compression:

Stored size: 1.77 KB

Contents

module UniverseCompiler
  module Entity

    module FieldManagement

      attr_accessor :auto_create_fields

      def method_missing(method_name, *args)
        if auto_create_fields
          candidate_field_name = method_name
          method_name.to_s.match (/^(?<field_name>[^=]+)\s*=?$/) do |md|
            candidate_field_name = md['field_name'].to_sym
          end
          define_field_accessor candidate_field_name
          raise "Invalid method '#{method_name}' in #{self}" unless self.respond_to? method_name
          self.send method_name, *args
        else
          super(method_name, *args)
        end
      end

      private

      def define_known_fields_accessors
        self.class.fields_constraints.each do |field_name, constraints|
          define_field_accessor field_name
          if fields[field_name].nil?
            fields[field_name] = [] if constraints[:has_many] || constraints[:is_array]
            fields[field_name] = {} if constraints[:is_hash]
          end
        end
      end

      def define_field_accessor(field_name)
        metaclass = class << self; self ; end
        UniverseCompiler.logger.debug 'Defining field accessor %s on class %s (%s)' % [field_name, metaclass, self.type]
        if self.respond_to? field_name or self.respond_to? "#{field_name}="
          UniverseCompiler.logger.warn "Cannot define '#{field_name}' or '#{field_name}=' which already exist(s) on class '#{metaclass}' !"
        else
          metaclass.instance_eval do
            define_method field_name do
              fields[field_name]
            end
          end
          metaclass.instance_eval do
            define_method "#{field_name}=" do |value|
              fields[field_name] = value
            end
          end
        end
      end

    end

  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
universe_compiler-0.3.2 lib/universe_compiler/entity/field_management.rb
universe_compiler-0.3.1 lib/universe_compiler/entity/field_management.rb
universe_compiler-0.3.0 lib/universe_compiler/entity/field_management.rb
universe_compiler-0.2.16 lib/universe_compiler/entity/field_management.rb
universe_compiler-0.2.15 lib/universe_compiler/entity/field_management.rb
universe_compiler-0.2.14 lib/universe_compiler/entity/field_management.rb
universe_compiler-0.2.13 lib/universe_compiler/entity/field_management.rb
universe_compiler-0.2.12 lib/universe_compiler/entity/field_management.rb
universe_compiler-0.2.11 lib/universe_compiler/entity/field_management.rb