Module: DataMapper::Is::Entity::ClassMethods

Defined in:
lib/dm-appengine/is_entity.rb

Instance Method Summary collapse

Instance Method Details

#ancestor_property(name) ⇒ Object



77
78
79
80
81
82
# File 'lib/dm-appengine/is_entity.rb', line 77

def ancestor_property(name)
  property name, Property::AncestorKey
  # We don't want to ever set this. It's just for queries.
  undef_method name
  undef_method :"#{name}="
end

#belongs_to_entity(name, add_id_property = true) ⇒ Object

Polymorphic belongs_to hack. (Datamapper doesn’t support polymorphic associations, probably by design.) We already have the type in the key_name anyway. has(n) works at the other end, just set child_key.



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/dm-appengine/is_entity.rb', line 101

def belongs_to_entity(name, add_id_property=true)
  key_getter = :"#{name}_id"
  key_setter = :"#{key_getter}="
  variable = :"@#{name}"
  
  if add_id_property
    property key_getter, Property::Key
  end
  
  define_method(name) do
    value = instance_variable_get(variable)
    return value if value
    
    key = send(key_getter)
    # All keys are polymorphic
    value = Extlib::Inflection.constantize(Extlib::Inflection.singularize(key.kind)).get(key)
    instance_variable_set(variable, value)
  end
  
  define_method(:"#{name}=") do |value|
    send(key_setter, value.key.first)
    instance_variable_set(variable, value)
  end
end

#descendants_property(name) ⇒ Object

Being somewhat more rigid here, because this really isn’t that complicated (yet). TODO: If possible, a typeless query would be nice here.



59
60
61
62
63
# File 'lib/dm-appengine/is_entity.rb', line 59

def descendants_property(name)
  define_method(name) do |type|
    type.all(:ancestor => self.key.first)
  end
end

#has_descendants(name, options = {}) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/dm-appengine/is_entity.rb', line 65

def has_descendants(name, options={})
  model = options.delete(:model)  # or leave it nil
  define_method(name) do
    model ||= Extlib::Inflection.constantize(
      Extlib::Inflection.camelize(
        Extlib::Inflection.singularize(name.to_s)
      )
    )
    model.all(options.merge(:ancestor => self.key.first))
  end
end

#parent_property(name) ⇒ Object



88
89
90
91
92
93
94
95
# File 'lib/dm-appengine/is_entity.rb', line 88

def parent_property(name)
  define_method("#{name}_id") do
    k = key.first
    k.kind_of?(AppEngine::Datastore::Key) && k.parent
  end
  
  belongs_to_entity(name, false)
end

#primary_key(name) ⇒ Object



84
85
86
# File 'lib/dm-appengine/is_entity.rb', line 84

def primary_key(name)
  property name, Property::Key, :key => true
end