require "dry-inflector" module PgGraph class Inflector #< Dry::Inflector def initialize() @inflector = Dry::Inflector.new end def pluralize(word) return word if plural? word result = @inflector.pluralize(word) if result == word word =~ /s$/ ? "#{word}es" : "#{word}s" else result end end # Note that DryInflector::singularize handles the special PgGraph # pluralization rules by default def singularize(word) @inflector.singularize(word) end # #plural? is defined using #singularize because #pluralize would cause # endless recursion def plural?(word) singularize(word) != word end def singular?(word) singularize(word) == word end def table2table_type(name) record_type2table_type(table2record_type(name)) end def table2record_type(name) singularize(name) end def table_type2table(name) record_type2table(table_type2record_type(name)) end def table_type2record_type(name) name[1..-2] end def record_type2table(name) if name =~ /s$/ name + "es" else pluralize(name) end end def record_type2table_type(name) type2array(name) end def type2array(name) "[#{name}]" end # Convert a column name to a field name by removing a '_id' at the end def column2field_name(column_name) # column_name.sub(/_id$|_kind$/, "") column_name.sub(/_id$/, "") end # Camelize string def camelize(s) s = s.sub(/^[a-z\d]*/) { |match| match.capitalize } s.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" } end # Remove module prefix from class names. Used in debugging def klass_name(qualified_klass_name) demodulize(qualified_klass_name) end # Types are both native postgres type and types from the information_schema def postgres_type2ruby_class(name) case name when "character varying", "varchar", "text", "uuid"; String when "smallint", "integer", "int4", "int2"; Integer when "double precision", "real"; Float when "numeric", "decimal"; BigDecimal when "bool", "boolean"; Boolean when "json"; Hash when "bytea"; String when "timestamp", "timestamp without time zone"; Time when /^_/; Array else raise "Unsupported postgres type: #{name.inspect} (FIXIT!)" end end SUPPORTED_RUBY_CLASSES = [String, Integer, Float, BigDecimal, Boolean, Hash, Time, NilClass, Array] end def self.inflector() @inflector ||= Inflector.new end end