lib/cfoundry/v2/model.rb in cfoundry-0.3.8 vs lib/cfoundry/v2/model.rb in cfoundry-0.3.9

- old
+ new

@@ -23,12 +23,12 @@ def to_one(name, opts = {}) obj = opts[:as] || name define_method(name) { - if manifest[:entity].key? name - @client.send(:"make_#{obj}", manifest[:entity][name]) + if @manifest && @manifest[:entity].key?(name) + @client.send(:"make_#{obj}", @manifest[:entity][name]) else @client.send( :"#{obj}_from", send("#{name}_url"), opts[:depth] || 1) @@ -54,12 +54,12 @@ plural_object = :"#{object}s" define_method(plural) { |*args| depth, query = args - if manifest[:entity].key?(plural) - objs = manifest[:entity][plural] + if @manifest && @manifest[:entity].key?(plural) && !depth + objs = @manifest[:entity][plural] if query find_by = query.keys.first find_val = query.values.first objs = objs.select { |o| o[:entity][find_by] == find_val } @@ -69,11 +69,11 @@ @client.send(:"make_#{object}", json) end else @client.send( :"#{plural_object}_from", - send("#{plural}_url"), + "/v2/#{object_name}s/#@guid/#{plural}", depth || opts[:depth], query) end } @@ -128,30 +128,62 @@ self.class.name.split("::").last.gsub( /([a-z])([A-Z])/, '\1_\2').downcase end + # this does a bit of extra processing to allow for + # `delete!' followed by `create!' def create! - @manifest = - @client.base.send( - :"create_#{object_name}", - self.class.defaults.merge(@manifest[:entity])) + payload = {} + self.class.defaults.merge(@manifest[:entity]).each do |k, v| + if v.is_a?(Hash) && v.key?(:metadata) + # skip; there's a _guid attribute already + elsif v.is_a?(Array) && v.all? { |x| + x.is_a?(Hash) && x.key?(:metadata) + } + singular = k.to_s.sub(/s$/, "") + + payload[:"#{singular}_guids"] = v.collect do |x| + if x.is_a?(Hash) && x.key?(:metadata) + x[:metadata][:guid] + else + x + end + end + elsif k.to_s.end_with?("_json") && v.is_a?(String) + payload[k] = JSON.parse(v) + elsif k.to_s.end_with?("_url") + else + payload[k] = v + end + end + + @manifest = @client.base.send(:"create_#{object_name}", payload) + @guid = @manifest[:metadata][:guid] + @diff.clear + true end def update!(diff = @diff) @client.base.send(:"update_#{object_name}", @guid, diff) + @diff.clear if diff == @diff + @manifest = nil end def delete! @client.base.send(:"delete_#{object_name}", @guid) + @guid = nil + + @diff.clear + if @manifest @manifest.delete :metadata end end @@ -160,10 +192,15 @@ true rescue CFoundry::APIError # TODO: NotFound would be better false end - def ==(other) + def eql?(other) other.is_a?(self.class) && @guid == other.guid + end + alias :== :eql? + + def hash + @guid.hash end end end