lib/travis/client/entity.rb in travis-1.0.3 vs lib/travis/client/entity.rb in travis-1.1.0
- old
+ new
@@ -7,18 +7,26 @@
attr_reader :attributes, :id, :session
attr_accessor :curry
MAP = {}
+ def self.relations
+ @relations ||= []
+ end
+
def self.subclasses
MAP.values.uniq
end
def self.subclass_for(key)
MAP.fetch(key)
end
+ def self.aka(name)
+ MAP[name.to_s] = self
+ end
+
def self.one(key = nil)
MAP[key.to_s] = self if key
@one ||= key.to_s
end
@@ -27,20 +35,37 @@
@many ||= key.to_s
end
def self.attributes(*list)
@attributes ||= []
+
list.each do |name|
name = name.to_s
+ fail "can't call an attribute id" if name == "id"
+
@attributes << name
define_method(name) { load_attribute(name) }
define_method("#{name}=") { |value| set_attribute(name, value) }
define_method("#{name}?") { !!send(name) }
end
+
@attributes
end
+ def self.time(*list)
+ list.each do |name|
+ define_method("#{name}=") { |value| set_attribute(name, time(value)) }
+ end
+ end
+
+ def self.has(*list)
+ list.each do |name|
+ relations << name
+ define_method(name) { relation(name.to_s) }
+ end
+ end
+
def self.inspect_info(name)
alias_method(:inspect_info, name)
private(:inspect_info)
end
@@ -71,15 +96,16 @@
def include?(key)
attributes.include? key or attribute_names.include? key.to_s
end
def reload
- session.reload(self)
+ relations.each { |e| session.reset(e) }
+ session.reset(self)
end
def load
- reload unless complete?
+ session.reload(self) unless complete?
end
def missing?(key)
return false unless include? key
!attributes.include?(key.to_s)
@@ -93,21 +119,39 @@
klass = self.class
klass = curry if curry and curry.name and curry.to_s.size < klass.to_s.size
"#<#{klass}: #{inspect_info}>"
end
+ def relations
+ self.class.relations.map { |r| public_send(r) }.flatten(1)
+ end
+
private
+ def relation(name)
+ name = name.to_s
+ entity = Entity.subclass_for(name)
+
+ if entity.many == name
+ Array(send("#{entity.one}_ids")).map do |id|
+ session.find_one(entity, id)
+ end
+ else
+ id = send("#{name}_id")
+ session.find_one(entity, id) unless id.nil?
+ end
+ end
+
def inspect_info
id
end
def set_attribute(name, value)
attributes[name.to_s] = value
end
def load_attribute(name)
- reload if missing? name
+ session.reload(self) if missing? name
attributes[name.to_s]
end
# shamelessly stolen from sinatra
def time(value)