forked from hashie/hashie
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
A bit of untested unfinished work on structure.
- Loading branch information
Michael Bleigh
committed
Oct 15, 2011
1 parent
5513b96
commit 1b59d29
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |