summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorMichael Bleigh <michael@intridea.com>2011-10-15 02:28:20 -0500
committerMichael Bleigh <michael@intridea.com>2011-10-15 02:28:20 -0500
commit1b59d29523d76c2c3bb16173a36e5145b6f117d9 (patch)
tree36b643dde22f52ac828e27c882d8f4d64d73961b /lib
parent5513b967b2114c1c2fe70b867d539493ff24d91b (diff)
downloadhashie-1b59d29523d76c2c3bb16173a36e5145b6f117d9.tar.gz
A bit of untested unfinished work on structure.
Diffstat (limited to 'lib')
-rw-r--r--lib/hashie/extensions/structure.rb47
1 files changed, 47 insertions, 0 deletions
diff --git a/lib/hashie/extensions/structure.rb b/lib/hashie/extensions/structure.rb
new file mode 100644
index 0000000..adb776b
--- /dev/null
+++ b/lib/hashie/extensions/structure.rb
@@ -0,0 +1,47 @@
+module Hashie
+ module Extensions
+ # The Structure extension provides facilities for declaring
+ # properties that a Hash can have. This provides for the
+ # creation of structures that still behave like hashes but
+ # do not allow setting non-allowed keys.
+ #
+ # @example
+ # class RestrictedHash < Hash
+ # include Hashie::Extensions::MergeInitializer
+ # include Hashie::Extensions::Structure
+ #
+ # key :first
+ # key :second, :default => 'foo'
+ # end
+ #
+ # h = RestrictedHash.new(:first => 1)
+ # h[:first] # => 1
+ # h[:second] # => 'foo'
+ # h[:third] # => ArgumentError
+ #
+ module Structure
+ def self.included(base)
+ base.extend ClassMethods
+ base.class_eval do
+ @permitted_keys = superclass.permitted_keys if superclass.respond_to?(:permitted_keys)
+ end
+ end
+
+ module ClassMethods
+ def key(key, options = {})
+ (@permitted_keys ||= []) << key
+
+ if options[:default]
+ (@default_values ||= {})[key] = options.delete(:default)
+ end
+
+ permitted_keys
+ end
+
+ def permitted_keys
+ @permitted_keys
+ end
+ end
+ end
+ end
+end