本文整理汇总了Golang中github.com/serenize/snaker.CamelToSnake函数的典型用法代码示例。如果您正苦于以下问题:Golang CamelToSnake函数的具体用法?Golang CamelToSnake怎么用?Golang CamelToSnake使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CamelToSnake函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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...)
}
开发者ID:yonglehou,项目名称:micro,代码行数:30,代码来源:web.go
示例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")
}
}
开发者ID:tksasha,项目名称:go-balance-backend,代码行数:25,代码来源:uniqueness_of.go
示例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")
}
}
开发者ID:wawandco,项目名称:transporter,代码行数:31,代码来源:generate.go
示例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
}
开发者ID:likestripes,项目名称:pacific,代码行数:32,代码来源:postgres.go
示例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
}
开发者ID:ivanol,项目名称:grapi,代码行数:10,代码来源:utils.go
示例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
}
开发者ID:ivanol,项目名称:grapi,代码行数:11,代码来源:utils.go
示例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)
}
开发者ID:tksasha,项目名称:go-balance-backend,代码行数:9,代码来源:errors.go
示例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
}
开发者ID:ryanzec,项目名称:going,代码行数:10,代码来源:common.go
示例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
}
开发者ID:md14454,项目名称:kapacitor,代码行数:55,代码来源:main.go
示例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
}
开发者ID:aacanakin,项目名称:qb,代码行数:19,代码来源:engine.go
示例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
}
开发者ID:knq,项目名称:xo,代码行数:55,代码来源:funcs.go
示例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
}
开发者ID:thesyncim,项目名称:xo,代码行数:24,代码来源:templates.go
示例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())
}
}
开发者ID:md14454,项目名称:kapacitor,代码行数:69,代码来源:main.go
示例14: nodeNameToLink
func nodeNameToLink(name string) string {
return fmt.Sprintf("%s/%s/", absPath, snaker.CamelToSnake(name))
}
开发者ID:md14454,项目名称:kapacitor,代码行数:3,代码来源:main.go
示例15: PropertyToField
func PropertyToField(s string) string {
mediary := snaker.CamelToSnake(s)
return snaker.SnakeToCamel(mediary)
}
开发者ID:nicholasray,项目名称:sandstone,代码行数:5,代码来源:translator.go
示例16: PropertyToColumn
func PropertyToColumn(s string) string {
return snaker.CamelToSnake(s)
}
开发者ID:nicholasray,项目名称:sandstone,代码行数:3,代码来源:translator.go
示例17: underscore
func underscore(s string) string {
return snaker.CamelToSnake(s) + ".go"
}
开发者ID:twstrike,项目名称:gotk-gen,代码行数:3,代码来源:gen.go
示例18: nodeNameToLink
func nodeNameToLink(name string) string {
return fmt.Sprintf("%s/%s/", config.Root, snaker.CamelToSnake(name))
}
开发者ID:wutaizeng,项目名称:kapacitor,代码行数:3,代码来源:main.go
示例19: Snakecase
func Snakecase(s string) string {
return snaker.CamelToSnake(s)
}
开发者ID:wlMalk,项目名称:gorator,代码行数:3,代码来源:util.go
示例20: GetFieldInfo
// Get the information for a struct field.
//
// The format is as follows:
//
// Field SomeType `form:"TYPE[,required][,autofocus][,.htmlClass][,#htmlID][,<int>][,<int>!]"`
//
// The integer tag expresses a field size. The integer tag with "!" expresses a maximum length.
//
// TYPE is the HTML field type. For non-<input/> types, use the tag name ("select", "textarea", etc.)
//
// Many HTML classes may be specified.
// If the HTML ID is not specified, the struct field name is used as the field name and HTML ID.
// Otherwise, the HTML ID is used as the field name and HTML ID.
//
// The following additional field tags are also supported:
//
// fmsg: Format message, shown on validation error.
// pattern: Regexp to enforce on client and server.
// placeholder: Placeholder string.
// label: Label string.
// set: <select> value set.
//
func GetFieldInfo(sf reflect.StructField) FieldInfo {
fi := FieldInfo{
FName: sf.Name,
}
tags := strings.Split(sf.Tag.Get("form"), ",")
fi.Type = tags[0]
for _, v := range tags[1:] {
switch {
case v == "required":
fi.Required = true
case v == "autofocus":
fi.Autofocus = true
case v == "":
case v[0] == '.':
fi.Classes = append(fi.Classes, v[1:])
case v[0] == '#':
fi.ID = v[1:]
case v[0] >= '0' && v[0] <= '9':
strict := false
if v[len(v)-1] == '!' {
strict = true
v = v[0 : len(v)-1]
} else if idx := strings.IndexByte(v, 'x'); idx >= 0 {
v2 := v[idx+1:]
n, err := strconv.ParseUint(v2, 10, 31)
if err == nil {
fi.VSize = int(n)
}
v = v[0:idx]
}
n, err := strconv.ParseUint(v, 10, 31)
if err == nil {
if strict {
fi.MaxLength = int(n)
} else {
fi.Size = int(n)
}
}
default:
if fi.Type == "" {
fi.Type = v
}
}
}
fi.FormatMessage = sf.Tag.Get("fmsg")
fi.Pattern = sf.Tag.Get("pattern")
fi.ValueSet = sf.Tag.Get("set")
if fi.ID == "" {
fi.Name = fi.FName
fi.Name = snaker.CamelToSnake(fi.Name)
fi.ID = fi.Name
} else {
fi.Name = fi.ID
}
fi.Label = sf.Tag.Get("label")
if fi.Label == "-" {
fi.Label = ""
} else if fi.Label == "" {
fi.Label = fi.FName
}
fi.Placeholder = sf.Tag.Get("placeholder")
if fi.Placeholder == "-" {
fi.Placeholder = ""
} else if fi.Placeholder == "" {
fi.Placeholder = fi.Label
}
return fi
}
开发者ID:hlandau,项目名称:degoutils,代码行数:98,代码来源:info.go
注:本文中的github.com/serenize/snaker.CamelToSnake函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论