Sha256: a2b6d0a05b17b5decdff3a5106f9196c7a60e7134dcfd702a6bcfe4579a176f7

Contents?: true

Size: 933 Bytes

Versions: 3

Compression:

Stored size: 933 Bytes

Contents

module Taketo
  module Support

    module Inflections
      extend self

      def to_singular(thing)
        str = name(thing)
        str.chop! if plural?(str)
        str.to_sym
      end

      def to_plural(thing)
        str = name(thing)
        str << "s" unless plural?(str)
        str.to_sym
      end

      def to_class(thing, nesting = Module.nesting.first || Object)
        nesting.const_get(class_name_from_string(to_singular(thing)))
      end

      private

      def name(thing)
        thing.is_a?(Class) ? name_from_class(thing) : thing.to_s
      end

      def name_from_class(klass)
        klass.name.gsub(/[A-Za-z0-9]+::/, "").gsub(/[A-Z][^A-Z]*/) { |s| s.gsub("::", "").downcase + "_" }.chop
      end

      def class_name_from_string(singular)
        singular.to_s.gsub(/(^|_)\w/) { |s| s.gsub(/_/, "").capitalize }
      end

      def plural?(str)
        str =~ /s$/
      end
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
taketo-0.3.1 lib/taketo/support/inflections.rb
taketo-0.3.0 lib/taketo/support/inflections.rb
taketo-0.2.0 lib/taketo/support/inflections.rb