Class: NsOptions::RootMethods

Inherits:
Object
  • Object
show all
Defined in:
lib/ns-options/root_methods.rb

Instance Method Summary collapse

Constructor Details

#initialize(define_on, name) ⇒ RootMethods

This class handles defining a root namespace class method for classes or modules and an additional instance method for classes. For classes, the instance method will build an entirely new namespace, distinct from the class level namespace but with an identical definition



11
12
13
14
15
# File 'lib/ns-options/root_methods.rb', line 11

def initialize(define_on, name)
  @define_on, @name     = define_on, name
  @class_meth_extension = Module.new
  @instance_meth_mixin  = Module.new
end

Instance Method Details

#define(io = nil, from_caller = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ns-options/root_methods.rb', line 21

def define(io=nil, from_caller=nil)
  validate(io || $stdout, from_caller || caller)

  # covers defining the class-level method on Modules or Classes
  @class_meth_extension.class_eval class_meth_extension_code
  @define_on.send :extend, @class_meth_extension

  if define_on_class?
    # covers defining the instance-level method on Classes
    @instance_meth_mixin.class_eval instance_meth_mixin_code
    @define_on.send :include, @instance_meth_mixin
  end
end

#define_on_class?Boolean

Returns:



17
18
19
# File 'lib/ns-options/root_methods.rb', line 17

def define_on_class?
  !!@define_on.kind_of?(::Class)
end

#validate(io, from_caller) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/ns-options/root_methods.rb', line 35

def validate(io, from_caller)
  return true unless [:options, :opts, :namespace, :ns].include?(@name.to_sym)

  io.puts "WARNING: Defining an option namespace with the name `#{@name}'"\
          " overwrites a method NsOptions depends on.  You won't be able to"\
          " define any additional option namespaces using the `#{@name}'"\
          " method."
  io.puts from_caller.first
  false
end