diff --git a/app/models/vm_or_template.rb b/app/models/vm_or_template.rb index 127b27c00b8..76615609480 100644 --- a/app/models/vm_or_template.rb +++ b/app/models/vm_or_template.rb @@ -1521,9 +1521,11 @@ def changed_vm_value?(options) # Hardware Disks/Memory storage methods # - virtual_delegate :allocated_disk_storage, :used_disk_storage, :provisioned_storage, + virtual_delegate :allocated_disk_storage, :used_disk_storage, :to => :hardware, :allow_nil => true, :uses => {:hardware => :disks} + virtual_delegate :provisioned_storage, :to => :hardware, :allow_nil => true, :default => 0 + def used_storage used_disk_storage.to_i + ram_size_in_bytes end diff --git a/lib/extensions/ar_virtual.rb b/lib/extensions/ar_virtual.rb index f2b57d48fe4..6e5b1a0f476 100644 --- a/lib/extensions/ar_virtual.rb +++ b/lib/extensions/ar_virtual.rb @@ -147,7 +147,7 @@ def define_delegate(method_name, method, to: nil, allow_nil: nil, default: nil) if allow_nil method_def = <<-METHOD def #{method_name}(#{definition}) - return self[:#{method_name}] if has_attribute?(:#{method_name}) + return self[:#{method_name}]#{default} if has_attribute?(:#{method_name}) _ = #{to} if !_.nil? || nil.respond_to?(:#{method}) _.#{method}(#{definition}) @@ -159,7 +159,7 @@ def #{method_name}(#{definition}) method_def = <<-METHOD def #{method_name}(#{definition}) - return self[:#{method_name}] if has_attribute?(:#{method_name}) + return self[:#{method_name}]#{default} if has_attribute?(:#{method_name}) _ = #{to} _.#{method}(#{definition})#{default} rescue NoMethodError => e diff --git a/spec/models/vm_or_template_spec.rb b/spec/models/vm_or_template_spec.rb index fd03ae11dad..e420f44976d 100644 --- a/spec/models/vm_or_template_spec.rb +++ b/spec/models/vm_or_template_spec.rb @@ -596,6 +596,22 @@ end end + describe "#provisioned_storage" do + context "with no hardware" do + let(:vm) { FactoryGirl.create(:vm_vmware) } + + it "calculates in ruby" do + expect(vm.provisioned_storage).to eq(0.0) + end + + it "uses calculated (inline) attribute" do + vm # make sure the record is created + vm2 = VmOrTemplate.select(:id, :provisioned_storage).first + expect { expect(vm2.provisioned_storage).to eq(0) }.to match_query_limit_of(0) + end + end + end + describe ".ram_size", ".mem_cpu" do let(:vm) { FactoryGirl.create(:vm_vmware, :hardware => hardware) } let(:hardware) { FactoryGirl.create(:hardware, :memory_mb => 10) }