Module: Naming

Defined in:
lib/naming.rb,
lib/naming/meta.rb,
lib/naming/version.rb,
lib/naming/name-set.rb

Overview

Naming is a module for generating naming classes that consist by name and value. Naming classes are generated dynamically when you refer it.

Examples:

#
# naming object of A with the value 123
#
a = Naming.A(123)
a.value #=> 123
a.name  #=> :A
a.class #=> Naming::A
#
# collect objects by name
#
list = [
  Naming.A(1),
  Naming.B(2),
  "abc",
  Naming.A(3),
  123,
  nil
]
# collect values of A objects
Naming::A.values(list) #=> [1, 3]
# collect values of B objects
Naming::B.values(list) #=> [2]
# collect objects excluding naming objects
Naming.others(list)    #=> ["abc", 123, nil]
#
# case control flow with name
#
def message(obj)
  case obj
  when Naming::A
    "This is case A: %s" % obj.value
  when Naming::B
    "This is case B: %s" % obj.value
  else
    "This is case others: %s" % obj
  end
end
message(Naming.A(1)) #=> "This is case A: 1"
message(Naming.B(2)) #=> "This is case B: 2"
message(true) #=> "This is case others: true"

Defined Under Namespace

Classes: Meta, NameSet

Constant Summary collapse

VERSION =

version of this library

"0.1.0"

Class Method Summary collapse

Class Method Details

.[](*names) ⇒ NameSet

Return the name set object.

Parameters:

  • names (Array<Symbol>)

    names

Returns:



102
103
104
# File 'lib/naming.rb', line 102

def [](*names)
  NameSet.new(*names)
end

.const_missing(name) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Generate a new naming class.



69
70
71
72
73
74
75
76
77
# File 'lib/naming.rb', line 69

def const_missing(name)
  cls = Class.new(Meta)
  self.singleton_class.class_exec do
    define_method(name) do |value|
      cls.new(value)
    end
  end
  const_set(name, cls)
end

.method_missing(name, *args) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Generate a new naming class and call the constructor with value.



61
62
63
64
# File 'lib/naming.rb', line 61

def method_missing(name, *args)
  const_get(name)
  send(name, *args)
end

.others(array) ⇒ Object

Collect objects from the array excluding naming objects.

Examples:

Naming.others([
  Naming.A(1),
  Naming.B(2),
  "abc",
  Naming.A(3),
  123,
  nil
]) #=> ["abc", 123, nil]

Parameters:

  • array (Array)

    collection target array



93
94
95
# File 'lib/naming.rb', line 93

def others(array)
  array.select{|elt| not(elt.kind_of?(Meta))}
end