本文整理汇总了Golang中github.com/serenize/snaker.CamelToSnake函数的典型用法代码示例。如果您正苦于以下问题:Golang CamelToSnake函数的具体用法?Golang CamelToSnake怎么用?Golang CamelToSnake使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CamelToSnake函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: formatEndpoint
func formatEndpoint(v *registry.Value, r int) string {
// default format is tabbed plus the value plus new line
fparts := []string{"", "%s %s", "\n"}
for i := 0; i < r+1; i++ {
fparts[0] += "\t"
}
// its just a primitive of sorts so return
if len(v.Values) == 0 {
return fmt.Sprintf(strings.Join(fparts, ""), snaker.CamelToSnake(v.Name), v.Type)
}
// this thing has more things, it's complex
fparts[1] += " {"
vals := []interface{}{snaker.CamelToSnake(v.Name), v.Type}
for _, val := range v.Values {
fparts = append(fparts, "%s")
vals = append(vals, formatEndpoint(val, r+1))
}
// at the end
l := len(fparts) - 1
for i := 0; i < r+1; i++ {
fparts[l] += "\t"
}
fparts = append(fparts, "}\n")
return fmt.Sprintf(strings.Join(fparts, ""), vals...)
}
示例2: ValidateUniquenessOf
func ValidateUniquenessOf(resource Resource, attribute string) {
reflected := reflect.ValueOf(resource).Elem()
value := reflect.Indirect(reflected).FieldByName(attribute)
field := snaker.CamelToSnake(attribute)
var count int
table := DB.NewScope(resource).TableName()
query := DB.Table(table).Where("LOWER("+field+")=?", strings.ToLower(value.String()))
id := reflect.Indirect(reflected).FieldByName("ID").Int()
if id > 0 {
query = query.Not("id", id)
}
query.Count(&count)
if count > 0 {
resource.Errors().Add(attribute, "already exists")
}
}
示例3: Generate
//Generate generates a migration on the migrations folder
func Generate(c *cli.Context) {
setupTestingEnv()
base := os.Getenv("TRANS_TESTING_FOLDER")
name := "migration"
if c.App != nil && len(c.Args()) > 0 {
name = c.Args().First()
}
name = snaker.CamelToSnake(name)
identifier := time.Now().UnixNano()
migration := MigrationData{
Identifier: identifier,
Name: name,
}
buff := bytes.NewBufferString("")
tmpl, _ := template.New("migration").Parse(utils.MigrationTemplate)
_ = tmpl.Execute(buff, migration)
fileName := strconv.FormatInt(identifier, 10) + "_" + name + ".go"
path := filepath.Join(base, "db", "migrations", fileName)
err := ioutil.WriteFile(path, buff.Bytes(), generatedFilePermissions)
if err != nil {
log.Println(err)
log.Println("| Could not write migration file, please check db/migrations folder exists")
}
}
示例4: createQuery
func (query Query) createQuery() (q *gorm.DB) {
query.tableify()
q = query.Context.Connection.Table(query.tableName)
for _, ancestor := range query.Ancestors {
filter_by_str := ancestor.primaryKey() + " = ?"
q = q.Where(filter_by_str, ancestor.key())
}
for filter_by, value := range query.Filters {
filter_by = snaker.CamelToSnake(filter_by)
filter_by_str := filter_by + " ?"
q = q.Where(filter_by_str, value)
}
if query.Limit != 0 {
q = q.Limit(query.Limit)
}
if query.Offset != 0 {
q = q.Offset(query.Offset)
}
if query.Order != "" {
direction, column := order_by(query.Order)
order_str := column + " " + direction
q = q.Order(order_str)
}
return q
}
示例5: pluralCamelNameType
// pluralCamelNameType takes a type, and returns its type converted
// to camel_case and pluralised.
func pluralCamelNameType(typ reflect.Type) string {
t := fmt.Sprintf("%v", typ)
a := strings.Split(t, ".")
t1 := a[len(a)-1]
t2 := snaker.CamelToSnake(t1)
t3 := inflector.Pluralize(t2)
return t3
}
示例6: pluralCamelName
// pluralCamelName takes an interface, and returns its type converted
// to camel_case and pluralised. eg. pluralCamelName(ImportantPerson{})
// should return "important_people"
func pluralCamelName(i interface{}) string {
t := fmt.Sprintf("%T", i)
a := strings.Split(t, ".")
t1 := a[len(a)-1]
t2 := snaker.CamelToSnake(t1)
t3 := inflector.Pluralize(t2)
return t3
}
示例7: MarshalJSON
func (e Errors) MarshalJSON() ([]byte, error) {
for key, value := range e.collection {
delete(e.collection, key)
e.collection[snaker.CamelToSnake(key)] = value
}
return json.Marshal(e.collection)
}
示例8: GenerateKey
func GenerateKey(s string) string {
key := CustomKeys[s]
if key != "" {
return key
}
key = strings.Replace(s, " ", "", -1)
key = strings.Replace(key, "-", "", -1)
key = snaker.CamelToSnake(key)
return key
}
示例9: Render
func (n *Node) Render(buf *bytes.Buffer, r Renderer, nodes map[string]*Node, index int) error {
header := fmt.Sprintf(`---
title: %s
note: Auto generated by tickdoc
menu:
kapacitor_02:
name: %s
identifier: %s
weight: %d
parent: tick
---
`,
n.Name,
strings.Replace(n.Name, "Node", "", 1),
snaker.CamelToSnake(n.Name),
(index+1)*indexWidth,
)
buf.Write([]byte(header))
renderDoc(buf, nodes, r, n.Doc)
// Properties
if len(n.Properties) > 0 {
r.Header(buf, func() bool { buf.Write([]byte("Properties")); return true }, 2, "")
r.Paragraph(buf, func() bool {
buf.Write([]byte("Property methods modify state on the calling node. They do not add another node to the pipeline, and always return a reference to the calling node."))
return true
})
renderProperties(buf, r, n.Properties, nodes, 3, "node")
}
// Methods
if len(n.Methods) > 0 {
r.Header(buf, func() bool { buf.Write([]byte("Chaining Methods")); return true }, 2, "")
r.Paragraph(buf, func() bool {
buf.Write([]byte("Chaining methods create a new node in the pipeline as a child of the calling node. They do not modify the calling node."))
return true
})
methods := make([]string, len(n.Methods))
i := 0
for name, _ := range n.Methods {
methods[i] = name
i++
}
sort.Strings(methods)
for _, name := range methods {
n.Methods[name].Render(buf, r, nodes)
buf.Write([]byte("\n"))
}
}
return nil
}
示例10: New
// New generates a new engine and returns it as an engine pointer
func New(driver string, dsn string) (*Engine, error) {
conn, err := sqlx.Open(driver, dsn)
if err != nil {
return nil, err
}
// set name mapper function
conn.MapperFunc(func(name string) string {
return snaker.CamelToSnake(name)
})
return &Engine{
dialect: NewDialect(driver),
dsn: dsn,
db: conn,
logger: &DefaultLogger{LDefault, log.New(os.Stdout, "", -1)},
}, err
}
示例11: goparamlist
// goparamlist converts a list of fields into their named Go parameters,
// skipping any Field with Name contained in ignoreNames. addType will cause
// the go Type to be added after each variable name. addPrefix will cause the
// returned string to be prefixed with ", " if the generated string is not
// empty.
//
// Any field name encountered will be checked against goReservedNames, and will
// have its name substituted by its corresponding looked up value.
//
// Used to present a comma separated list of Go variable names for use with as
// either a Go func parameter list, or in a call to another Go func.
// (ie, ", a, b, c, ..." or ", a T1, b T2, c T3, ...").
func (a *ArgType) goparamlist(fields []*Field, addPrefix bool, addType bool, ignoreNames ...string) string {
ignore := map[string]bool{}
for _, n := range ignoreNames {
ignore[n] = true
}
i := 0
vals := []string{}
for _, f := range fields {
if ignore[f.Name] {
continue
}
s := "v" + strconv.Itoa(i)
if len(f.Name) > 0 {
n := strings.Split(snaker.CamelToSnake(f.Name), "_")
s = strings.ToLower(n[0]) + f.Name[len(n[0]):]
}
// check go reserved names
if r, ok := goReservedNames[strings.ToLower(s)]; ok {
s = r
}
// add the go type
if addType {
s += " " + a.retype(f.Type)
}
// add to vals
vals = append(vals, s)
i++
}
// concat generated values
str := strings.Join(vals, ", ")
if addPrefix && str != "" {
return ", " + str
}
return str
}
示例12: shortname
// shortname checks the passed type against the ShortNameTypeMap and returns
// the value for it. If the type is not found, then the value is calculated and
// stored in the ShortNameTypeMap for use in the future.
func shortname(typ string) string {
var v string
var ok bool
// check short name map
if v, ok = ShortNameTypeMap[typ]; !ok {
// calc the short name
u := []string{}
for _, s := range strings.Split(strings.ToLower(snaker.CamelToSnake(typ)), "_") {
if len(s) > 0 && s != "id" {
u = append(u, s[:1])
}
}
v = strings.Join(u, "")
// store back in short name map
ShortNameTypeMap[typ] = v
}
return v
}
示例13: main
func main() {
if len(os.Args) != 4 {
fmt.Println("Usage: tickdoc absPath path/to/golang/package output/dir")
fmt.Println()
fmt.Println("absPath - the absolute path of rendered documentation, used to generate links.")
os.Exit(1)
}
absPath = os.Args[1]
dir := os.Args[2]
out := os.Args[3]
fset := token.NewFileSet() // positions are relative to fset
skipTest := func(fi os.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")
}
pkgs, err := parser.ParseDir(fset, dir, skipTest, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
nodes := make(map[string]*Node)
for _, pkg := range pkgs {
f := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates|ast.FilterUnassociatedComments|ast.FilterImportDuplicates)
ast.Inspect(f, func(n ast.Node) bool {
switch decl := n.(type) {
case *ast.GenDecl:
handleGenDecl(nodes, decl)
case *ast.FuncDecl:
handleFuncDecl(nodes, decl)
}
return true
})
}
ordered := make([]string, 0, len(nodes))
for name, node := range nodes {
if name == "" || !ast.IsExported(name) {
continue
}
if node.Embedded {
err := node.Embed(nodes)
if err != nil {
log.Fatal(err)
}
} else {
ordered = append(ordered, name)
node.Flatten(nodes)
}
}
sort.Strings(ordered)
r := markdown.NewRenderer()
for i, name := range ordered {
var buf bytes.Buffer
n := nodes[name]
n.Render(&buf, r, nodes, i)
filename := path.Join(out, snaker.CamelToSnake(name)+".md")
log.Println("Writing file:", filename, i)
f, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
defer f.Close()
f.Write(buf.Bytes())
}
}
示例14: nodeNameToLink
func nodeNameToLink(name string) string {
return fmt.Sprintf("%s/%s/", absPath, snaker.CamelToSnake(name))
}
示例15: PropertyToField
func PropertyToField(s string) string {
mediary := snaker.CamelToSnake(s)
return snaker.SnakeToCamel(mediary)
}