Module: OptStruct

Defined in:
lib/opt_struct.rb,
lib/opt_struct/version.rb,
lib/opt_struct/class_methods.rb,
lib/opt_struct/module_methods.rb,
lib/opt_struct/instance_methods.rb

Defined Under Namespace

Modules: ClassMethods, InstanceMethods, ModuleMethods

Constant Summary collapse

VERSION =
"1.0.2"

Class Method Summary collapse

Class Method Details

._inject_struct(target, source, args = [], defaults = {}, &callback) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/opt_struct.rb', line 7

def self._inject_struct(target, source, args = [], defaults = {}, &callback)
  structs = Array(source.instance_variable_get(:@_opt_structs)).dup
  if args.any? || defaults.any? || callback
    structs << [args, defaults, callback]
  end
  target.instance_variable_set(:@_opt_structs, structs)
  if target.is_a?(Class)
    target.instance_exec do
      extend ClassMethods
      attr_reader :options
      include InstanceMethods
    end
    structs.each do |s_args, s_defaults, s_callback|
      target.expect_arguments *s_args if s_args.any?
      target.options s_defaults       if s_defaults.any?
      target.class_exec(&s_callback)  if s_callback
    end
  else
    target.singleton_class.prepend ModuleMethods
  end
  target
end

.build(*args, **defaults, &callback) ⇒ Object



44
45
46
# File 'lib/opt_struct.rb', line 44

def self.build(*args, **defaults, &callback)
  _inject_struct(Module.new, self, args.map(&:to_sym), defaults, &callback)
end

.included(klass) ⇒ Object



30
31
32
33
# File 'lib/opt_struct.rb', line 30

def self.included(klass)
  _inject_struct(klass, self)
  super(klass)
end

.new(*args, **defaults, &callback) ⇒ Object



40
41
42
# File 'lib/opt_struct.rb', line 40

def self.new(*args, **defaults, &callback)
  _inject_struct(Class.new, self, args.map(&:to_sym), defaults, &callback)
end

.prepended(klass) ⇒ Object



35
36
37
38
# File 'lib/opt_struct.rb', line 35

def self.prepended(klass)
  _inject_struct(klass, self)
  super(klass)
end