lib/chef-api/schema.rb in chef-api-0.2.0 vs lib/chef-api/schema.rb in chef-api-0.2.1
- old
+ new
@@ -11,11 +11,10 @@
# @return [Hash]
#
attr_reader :attributes
attr_reader :ignored_attributes
- attr_reader :transformations
#
# The list of defined validators for this schema.
#
# @return [Array]
@@ -26,19 +25,14 @@
# Create a new schema and evaulte the block contents in a clean room.
#
def initialize(&block)
@attributes = {}
@ignored_attributes = {}
- @transformations = {}
+ @flavor_attributes = {}
@validators = []
- instance_eval(&block) if block
-
- @attributes.freeze
- @ignored_attributes.freeze
- @transformations.freeze
- @validators.freeze
+ unlock { instance_eval(&block) } if block
end
#
# The defined primary key for this schema. If no primary key is given, it
# is assumed to be the first item in the list.
@@ -48,10 +42,49 @@
def primary_key
@primary_key ||= @attributes.first[0]
end
#
+ # Create a lazy-loaded block for a given flavor.
+ #
+ # @example Create a block for Enterprise Chef
+ # flavor :enterprise do
+ # attribute :custom_value
+ # end
+ #
+ # @param [Symbol] id
+ # the id of the flavor to target
+ # @param [Proc] block
+ # the block to capture
+ #
+ # @return [Proc]
+ # the given block
+ #
+ def flavor(id, &block)
+ @flavor_attributes[id] = block
+ block
+ end
+
+ #
+ # Load the flavor block for the given id.
+ #
+ # @param [Symbol] id
+ # the id of the flavor to target
+ #
+ # @return [true, false]
+ # true if the flavor existed and was evaluted, false otherwise
+ #
+ def load_flavor(id)
+ if block = @flavor_attributes[id]
+ unlock { instance_eval(&block) }
+ true
+ else
+ false
+ end
+ end
+
+ #
# DSL method for defining an attribute.
#
# @param [Symbol] key
# the key to use
# @param [Hash] options
@@ -89,24 +122,29 @@
keys.each do |key|
@ignored_attributes[key.to_sym] = true
end
end
+ private
+
#
- # Transform an attribute onto another.
+ # @private
#
- # @example Transform the +:bacon+ attribute onto the +:ham+ attribute
- # transform :bacon, ham: true
+ # Helper method to duplicate and unfreeze all the attributes in the schema,
+ # yield control to the user for modification in the current context, and
+ # then re-freeze the variables for modification.
#
- # @example Transform an attribute with a complex transformation
- # transform :bacon, ham: ->(value) { value.split('__', 2).last }
- #
- # @param [Symbol] key
- # the attribute to transform
- # @param [Hash] options
- # the key-value pair of the transformations to make
- #
- def transform(key, options = {})
- @transformations[key.to_sym] = options
+ def unlock
+ @attributes = @attributes.dup
+ @ignored_attributes = @ignored_attributes.dup
+ @flavor_attributes = @flavor_attributes.dup
+ @validators = @validators.dup
+
+ yield
+
+ @attributes.freeze
+ @ignored_attributes.freeze
+ @flavor_attributes.freeze
+ @validators.freeze
end
end
end