Module: Naming

Defined in:
lib/naming.rb,
lib/naming/version.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

Constant Summary collapse

VERSION =

version of this library

"0.0.1"

Class Method Summary collapse

Class Method Details

.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.



147
148
149
150
151
152
153
154
155
# File 'lib/naming.rb', line 147

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.



139
140
141
142
# File 'lib/naming.rb', line 139

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



171
172
173
# File 'lib/naming.rb', line 171

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