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 # # Unsupported types: box, circle, interval, line, lseg, money, path, pg_lsn, pg_snapshot, point, polygon # def postgres_type2ruby_class(name) case name # Boolean when "bool", "boolean"; Boolean # Character types when "character", "char", "character varying", "varchar", "text"; String # Binary data when "bit", "bit varying", "varbit", "bytea"; String # Integer types when "bigint", "int8", "integer", "int", "int4", "smallint", "int2"; Integer # Float types when "double precision", "float8", "real", "float4", "float" ; Float # Decimal types when "numeric", "decimal"; BigDecimal # Temporal when "time", "time with time zone", "timetz", "time without time zone", "timestamp", "timestamp with time zone", "timestamptz", "timestamp without time zone"; Time when "date"; Date # Array when /^_/; Array # Serials when "bigserial", "serial8", "serial", "serial4", "smallserial", "serial2"; Integer # UUIDS when "uuid"; String # JSON when "json", "jsonb"; Hash # XML when "xml"; String # Special types when "cidr"; String when "inet"; String when "macaddr", "macaddr8"; String when "tsquery", "tsvector"; String else raise "PgGraph doesn't support the '#{name.inspect}' postgres type" end end SUPPORTED_RUBY_CLASSES = [String, Integer, Float, BigDecimal, Boolean, Hash, Time, NilClass, Array] end def self.inflector() @inflector ||= Inflector.new end end