Sha256: 0e81fabaf616275a6fdc8de485900274b4473b867db6c80d9bf2bb8030090147

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

# coding: utf-8

module COS

    module Struct
      class Base
        module AttrHelper

          # 动态创建必选参数
          def required_attrs(*s)
            define_method(:required_attrs) {s}
            attr_reader(*s)
          end

          # 动态创建可选参数
          def optional_attrs(*s)
            define_method(:optional_attrs) {s}
            attr_reader(*s)
          end
        end

        extend AttrHelper

        def initialize(options = {})
          # 意外参数检测
          unless optional_attrs.include?(:SKIP_EXTRA)
            extra_keys = options.keys - required_attrs - optional_attrs
            unless extra_keys.empty?
              raise AttrError, "Unexpected extra keys: #{extra_keys.join(', ')}"
            end
          end

          # 必选参数检测
          required_keys = required_attrs - options.keys
          unless required_keys.empty?
            raise AttrError, "Keys: #{required_keys.join(', ')} is Required"
          end

          # 动态创建实例变量
          (required_attrs + optional_attrs).each do |attr|
            instance_variable_set("@#{attr}", options[attr])
          end
        end

      end
    end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
cos-0.1.2 lib/cos/struct.rb
cos-0.1.1 lib/cos/struct.rb