Sha256: d754572d71142a8cde7ec68857953381dec4b0fa69a7da257087be4937deb773

Contents?: true

Size: 1.45 KB

Versions: 6

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true
class Russial
  module Dictionary
    module DynamicMethods
      def initialize(*)
        super
        generate_methods
        generate_aliases
        initialize_defaults
      end

      private

      def generate_methods
        keys.each do |key|
          name = key.name
          define_singleton_method(name) do
            path << name unless path.include? name
            get
          end
        end
      end

      def generate_aliases
        singleton_class.class_eval do
          superclass.config.aliases.each do |a, m|
            begin
              alias_method a, m
            rescue NameError
              next
            end
          end
        end
      end

      def get
        case (memoized_result = result)
        when Hash
          self
        when String
          soft_reset_path
          substitutions.empty? ? memoized_result : substitute(memoized_result)
        end
      end

      def substitute(word)
        substitutions.inject(word) do |result, (from, to)|
          result.gsub(from.to_s, to)
        end
      end

      def keys
        @keys ||= extract_keys(dictionary).flatten
      end

      def extract_keys(hash, scope = [])
        hash.map do |k, v|
          if v.is_a? Hash
            extract_keys(v, scope + [k]) << Key.new(k, scope)
          else
            [Key.new(k, scope)]
          end
        end
      end

      Key = Struct.new(:name, :scope)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
russial-0.10.0 lib/russial/dictionary/dynamic_methods.rb
russial-0.9.2 lib/russial/dictionary/dynamic_methods.rb
russial-0.9.0 lib/russial/dictionary/dynamic_methods.rb
russial-0.8.4 lib/russial/dictionary/dynamic_methods.rb
russial-0.8.3 lib/russial/dictionary/dynamic_methods.rb
russial-0.8.2 lib/russial/dictionary/dynamic_methods.rb