Sha256: 72030f0a67d55944f97ef5c1da968a12883c97ddd29b50dab1cb498dd90e9f42

Contents?: true

Size: 1.09 KB

Versions: 11

Compression:

Stored size: 1.09 KB

Contents

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

11 entries across 11 versions & 1 rubygems

Version Path
xot-0.3 lib/xot/const_symbol_accessor.rb
xot-0.2.1 lib/xot/const_symbol_accessor.rb
xot-0.2 lib/xot/const_symbol_accessor.rb
xot-0.1.42 lib/xot/const_symbol_accessor.rb
xot-0.1.41 lib/xot/const_symbol_accessor.rb
xot-0.1.40 lib/xot/const_symbol_accessor.rb
xot-0.1.39 lib/xot/const_symbol_accessor.rb
xot-0.1.38 lib/xot/const_symbol_accessor.rb
xot-0.1.37 lib/xot/const_symbol_accessor.rb
xot-0.1.36 lib/xot/const_symbol_accessor.rb
xot-0.1.35 lib/xot/const_symbol_accessor.rb