File: structure.rb

package info (click to toggle)
ruby-hashie 2.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 272 kB
  • ctags: 179
  • sloc: ruby: 1,898; makefile: 4
file content (47 lines) | stat: -rw-r--r-- 1,238 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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