Sha256: b411c844f2490bdc9f3801241f640a0f027b90c1aa1cc50e2911d574f3beda92

Contents?: true

Size: 1.79 KB

Versions: 2

Compression:

Stored size: 1.79 KB

Contents

require "active_support"
require "forwardable"

module BulldozeRenamer
  class StringInflector
    class StringDoesNotInflectToItselfError < ArgumentError; end

    extend Forwardable

    def self.active_support_inflections
      [:underscore, :camelize]
    end

    def self.inflections
      active_support_inflections + [:dasherize, :upcase, :js_camelize]
    end

    def_delegators ActiveSupport::Inflector, *StringInflector.active_support_inflections

    def initialize(current, target)
      @current = current
      @target = target
    end

    def upcase(w)
      underscore(w).upcase
    end

    def dasherize(w)
      ActiveSupport::Inflector.dasherize(underscore(w))
    end

    def js_camelize(w)
      c = camelize(w).dup
      c[0] = c[0].downcase
      c
    end

    def mappings
      result = {
        current_inflection: nil,
        target_inflection: nil,
        inflections: {}
      }
      StringInflector.inflections.each do |i|
        unless result[:current_inflection]
          if @current == send(i, @current)
            result[:current_inflection] = i
          end
        end

        unless result[:target_inflection]
          if @target == send(i, @target)
            result[:target_inflection] = i
          end
        end

        mapping = {
          current: send(i, @current),
          target: send(i, @target)
        }

        unless result[:inflections].
          values.
          map { |i| i[:current] }.
          include?(mapping[:current])
          result[:inflections][i] = mapping
        end
      end

      unless result[:current_inflection]
        raise StringDoesNotInflectToItselfError.new(@current)
      end

      unless result[:target_inflection]
        raise StringDoesNotInflectToItselfError.new(@target)
      end
      result
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bulldoze_renamer-0.0.2 lib/bulldoze_renamer/string_inflector.rb
bulldoze_renamer-0.0.1 lib/bulldoze_renamer/string_inflector.rb