Sha256: f15a1531cdf26a026c2c8296d2c88bb084317bd0ef579ae42fbefcd39508ce02

Contents?: true

Size: 1.11 KB

Versions: 13

Compression:

Stored size: 1.11 KB

Contents

# -*- coding: utf-8 -*-


module Xot


  module ConstSymbolAccessor

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

    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

    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

  end# ConstSymbolAccessor


end# Xot


class Module

  include Xot::ConstSymbolAccessor

end# Module

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
xot-0.1.34 lib/xot/const_symbol_accessor.rb
xot-0.1.33 lib/xot/const_symbol_accessor.rb
xot-0.1.32 lib/xot/const_symbol_accessor.rb
xot-0.1.31 lib/xot/const_symbol_accessor.rb
xot-0.1.30 lib/xot/const_symbol_accessor.rb
xot-0.1.29 lib/xot/const_symbol_accessor.rb
xot-0.1.28 lib/xot/const_symbol_accessor.rb
xot-0.1.27 lib/xot/const_symbol_accessor.rb
xot-0.1.26 lib/xot/const_symbol_accessor.rb
xot-0.1.25 lib/xot/const_symbol_accessor.rb
xot-0.1.24 lib/xot/const_symbol_accessor.rb
xot-0.1.23 lib/xot/const_symbol_accessor.rb
xot-0.1.22 lib/xot/const_symbol_accessor.rb