lib/chef/data_bag_item.rb in chef-0.9.12 vs lib/chef/data_bag_item.rb in chef-0.9.14.beta.1
- old
+ new
@@ -16,21 +16,25 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
+require 'forwardable'
+
require 'chef/config'
require 'chef/mixin/params_validate'
require 'chef/mixin/from_file'
require 'chef/couchdb'
require 'chef/index_queue'
require 'chef/data_bag'
require 'extlib'
-require 'json'
+require 'chef/json'
class Chef
class DataBagItem
+
+ extend Forwardable
include Chef::Mixin::FromFile
include Chef::Mixin::ParamsValidate
include Chef::IndexQueue::Indexable
@@ -57,10 +61,13 @@
EOJS
}
}
}
+ # Define all Hash's instance methods as delegating to @raw_data
+ def_delegators(:@raw_data, *(Hash.instance_methods - Object.instance_methods))
+
attr_accessor :couchdb_rev, :couchdb_id, :couchdb
attr_reader :raw_data
# Create a new Chef::DataBagItem
def initialize(couchdb=nil)
@@ -132,11 +139,17 @@
"raw_data" => self.raw_data
}
result["_rev"] = @couchdb_rev if @couchdb_rev
result.to_json(*a)
end
-
+
+ def self.from_hash(h)
+ item = new
+ item.raw_data = h
+ item
+ end
+
# Create a Chef::DataBagItem from JSON
def self.json_create(o)
bag_item = new
bag_item.data_bag(o["data_bag"])
o.delete("data_bag")
@@ -154,23 +167,25 @@
end
bag_item.raw_data = Mash.new(o["raw_data"])
bag_item
end
- # The Data Bag Item behaves like a hash - we pass all that stuff along to @raw_data.
- def method_missing(method_symbol, *args, &block)
- self.raw_data.send(method_symbol, *args, &block)
- end
-
# Load a Data Bag Item by name from CouchDB
def self.cdb_load(data_bag, name, couchdb=nil)
(couchdb || Chef::CouchDB.new).load("data_bag_item", object_name(data_bag, name))
end
# Load a Data Bag Item by name via RESTful API
def self.load(data_bag, name)
- Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("data/#{data_bag}/#{name}")
+ item = Chef::REST.new(Chef::Config[:chef_server_url]).get_rest("data/#{data_bag}/#{name}")
+ if item.kind_of?(DataBagItem)
+ item
+ else
+ item = from_hash(item)
+ item.data_bag(data_bag)
+ item
+ end
end
# Remove this Data Bag Item from CouchDB
def cdb_destroy
Chef::Log.debug "destroying data bag item: #{self.inspect}"
@@ -206,13 +221,24 @@
# Set up our CouchDB design document
def self.create_design_document(couchdb=nil)
(couchdb || Chef::CouchDB.new).create_design_document("data_bag_items", DESIGN_DOCUMENT)
end
-
+
+ def ==(other)
+ other.respond_to?(:to_hash) &&
+ other.respond_to?(:data_bag) &&
+ (other.to_hash == to_hash) &&
+ (other.data_bag.to_s == data_bag.to_s)
+ end
+
# As a string
def to_s
"data_bag_item[#{id}]"
+ end
+
+ def inspect
+ "data_bag_item[#{data_bag.inspect}, #{raw_data['id'].inspect}, #{raw_data.inspect}]"
end
def pretty_print(pretty_printer)
pretty_printer.pp({"data_bag_item('#{data_bag}', '#{id}')" => self.to_hash})
end