Sha256: 7273224ee9c7409c6d896db000f713b3d8e085dbd0665012f9af7c0a47b388e2

Contents?: true

Size: 1.3 KB

Versions: 5

Compression:

Stored size: 1.3 KB

Contents

# encoding: utf-8
require "gdatastore_mapper/relation"
require "gdatastore_mapper/associations/has_many"

module GdatastoreMapper
  module Associations
    extend ActiveSupport::Concern

    def self.included(klass)
      klass.include Associations
    end

    def has_many models
      self.class_eval("attr_accessor :#{models.to_s + '_id'}")

      define_method models do
        association = GdatastoreMapper::Associations::HasMany.new(self, models)
        belongings = GdatastoreMapper::Relation.new(self, association)
        if self.attributes.include?(id_ models) && !self.send(id_ models).nil?
          self.send(id_ models).each do |id|
            belongings << (models.to_s.classify.constantize.find id)
          end
        end
        belongings
      end
    end

    def belongs_to model
      add_belongs_to model
      self.class_eval("attr_accessor :#{model.to_s + '_id'}")

      define_method model do
        if self.attributes.include?(id_ model)
          model.to_s.classify.constantize.find self.send(id_ model)
        end
      end
    end

    def belongs_to_models
      @belongs_to_models
    end

    private

    def add_belongs_to(model)
      if @belongs_to_models.nil?
        @belongs_to_models = [model.to_s]
      else
        @belongs_to_models << model.to_s
      end
    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
gdatastore_mapper-0.1.8 lib/gdatastore_mapper/associations.rb
gdatastore_mapper-0.1.7 lib/gdatastore_mapper/associations.rb
gdatastore_mapper-0.1.6 lib/gdatastore_mapper/associations.rb
gdatastore_mapper-0.1.5 lib/gdatastore_mapper/associations.rb
gdatastore_mapper-0.1.4 lib/gdatastore_mapper/associations.rb