Module: Xot::ConstSymbolAccessor

Included in:
Module
Defined in:
lib/xot/const_symbol_accessor.rb

Instance Method Summary collapse

Instance Method Details

#const_symbol_accessor(name, **symbol2const) ⇒ Object



6
7
8
9
# File 'lib/xot/const_symbol_accessor.rb', line 6

def const_symbol_accessor(name, **symbol2const)
  const_symbol_writer name, **symbol2const
  const_symbol_reader name, **symbol2const
end

#const_symbol_reader(name, **symbol2const) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/xot/const_symbol_accessor.rb', line 27

def const_symbol_reader(name, **symbol2const)
  reader = name.intern
  getter = "cs_get_#{name}__".intern

  alias_method getter, reader
  private getter

  const2symbol = symbol2const.reduce({}) {|h, (k, v)| h[v] = k; h}

  define_method reader do
    const  = __send__ getter
    symbol = const2symbol[const]
    raise "'#{const}' is unknown value." unless symbol
    symbol
  end

  name
end

#const_symbol_writer(name, **symbol2const) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/xot/const_symbol_accessor.rb', line 11

def const_symbol_writer(name, **symbol2const)
  writer = "#{name}=".intern
  setter = "cs_set_#{name}__".intern

  alias_method setter, writer
  private setter

  define_method writer do |symbol|
    const = symbol2const[symbol]
    raise ArgumentError unless const
    __send__ setter, const
  end

  name
end