github.com/mpontillo/pop@v4.13.1+incompatible/genny/model/model.go (about)

     1  package model
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/gobuffalo/flect"
     7  	"github.com/gobuffalo/flect/name"
     8  	"github.com/gobuffalo/genny"
     9  	"github.com/gobuffalo/genny/gogen"
    10  	"github.com/gobuffalo/packr/v2"
    11  )
    12  
    13  // New returns a generator for creating a new model
    14  func New(opts *Options) (*genny.Generator, error) {
    15  	g := genny.New()
    16  
    17  	if err := opts.Validate(); err != nil {
    18  		return g, err
    19  	}
    20  
    21  	if err := g.Box(packr.New("github.com/gobuffalo/pop/genny/model/templates", "../model/templates")); err != nil {
    22  		return g, err
    23  	}
    24  
    25  	m := presenter{
    26  		Name:        name.New(opts.Name),
    27  		Encoding:    name.New(opts.Encoding),
    28  		Validations: validatable(opts.Attrs),
    29  		Imports:     buildImports(opts),
    30  	}
    31  
    32  	ctx := map[string]interface{}{
    33  		"opts":  opts,
    34  		"model": m,
    35  	}
    36  	help := map[string]interface{}{
    37  		"capitalize": flect.Capitalize,
    38  		"trim_package": func(t string) string {
    39  			i := strings.LastIndex(t, ".")
    40  			if i == -1 {
    41  				return t
    42  			}
    43  			return t[i+1:]
    44  		},
    45  	}
    46  
    47  	t := gogen.TemplateTransformer(ctx, help)
    48  	g.Transformer(t)
    49  	g.Transformer(genny.Replace("-name-", flect.Singularize(opts.Name)))
    50  	g.Transformer(genny.Replace("-path-", opts.Path))
    51  	return g, nil
    52  }