Module: FFI::DRY::ConstMap
- Included in:
- ConstFlagsMap
- Defined in:
- lib/ffi/dry.rb
Overview
ConstMap can be used to organize and lookup value to constant mappings and vice versa. Constants can be imported from a namespace based on a regular expression or other means.
Class Method Summary collapse
Instance Method Summary collapse
-
#[](arg) ⇒ Object
A flexible name to value lookup.
-
#list ⇒ Object
Generates a hash of all the constant names mapped to value.
-
#slurp_constants(nspace, prefix) ⇒ Object
When called from a module definition or class method, this method imports all the constants from # namespace ‘nspace’ that start with into the local namespace as constants named with whatever follows the prefix.
Class Method Details
.included(klass) ⇒ Object
315 316 317 |
# File 'lib/ffi/dry.rb', line 315 def self.included(klass) klass.extend(ConstMap) end |
Instance Method Details
#[](arg) ⇒ Object
A flexible name to value lookup.
325 326 327 328 329 330 331 |
# File 'lib/ffi/dry.rb', line 325 def [](arg) if arg.is_a? Integer list.invert[arg] elsif arg.is_a? String or arg.is_a? Symbol list[arg.to_s.upcase] end end |
#list ⇒ Object
Generates a hash of all the constant names mapped to value. Usually, it’s a good idea to override this like so to cache results in derived modules:
def list; @@list ||= super() ; end
339 340 341 |
# File 'lib/ffi/dry.rb', line 339 def list constants.inject({}){|h,c| h.merge! c => const_get(c) } end |
#slurp_constants(nspace, prefix) ⇒ Object
When called from a module definition or class method, this method imports all the constants from # namespace ‘nspace’ that start with into the local namespace as constants named with whatever follows the prefix. Only constant names that match [A-Z]+ are imported, the rest are ignored.
This method also yields the (short) constant name and value to a block if one is provided. The block works like […].select {|c,v| … } in that the value is not mapped if the block returns nil or false.
352 353 354 355 356 357 358 359 |
# File 'lib/ffi/dry.rb', line 352 def slurp_constants(nspace, prefix) nspace.constants.grep(/^(#{prefix}([A-Z][A-Z0-9_]+))$/) do c = $2 v = nspace.const_get($1) next if block_given? and not yield(c,v) const_set c, v end end |