github.com/bketelsen/buffalo@v0.9.5/generators/resource/resource.go (about)

     1  package resource
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/gobuffalo/buffalo/generators"
    10  	"github.com/gobuffalo/makr"
    11  	"github.com/markbates/inflect"
    12  )
    13  
    14  // New generates a new actions/resource file and a stub test.
    15  func New(data makr.Data) (*makr.Generator, error) {
    16  	g := makr.New()
    17  	files, err := generators.Find(filepath.Join(generators.TemplatesPath, "resource"))
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  	// Get the flags
    22  	useModel := data["useModel"].(string)
    23  	skipModel := data["skipModel"].(bool)
    24  	mimeType := data["mimeType"].(string)
    25  
    26  	tmplName := "resource-use_model"
    27  
    28  	if mimeType == "json" || mimeType == "xml" {
    29  		tmplName = "resource-json-xml"
    30  	} else if skipModel {
    31  		tmplName = "resource-name"
    32  	}
    33  
    34  	for _, f := range files {
    35  		// Adding the resource template to the generator
    36  		if strings.Contains(f.WritePath, tmplName) {
    37  			folder := data["filesPath"].(string)
    38  			if strings.Contains(f.WritePath, "actions") {
    39  				folder = data["actionsPath"].(string)
    40  			}
    41  
    42  			g.Add(makr.NewFile(strings.Replace(f.WritePath, tmplName, folder, -1), f.Body))
    43  		}
    44  		if mimeType == "html" {
    45  			// Adding the html templates to the generator
    46  			if strings.Contains(f.WritePath, "model-view-") {
    47  				targetPath := filepath.Join(
    48  					filepath.Dir(f.WritePath),
    49  					data["filesPath"].(string),
    50  					strings.Replace(filepath.Base(f.WritePath), "model-view-", "", -1),
    51  				)
    52  				g.Add(makr.NewFile(targetPath, f.Body))
    53  			}
    54  		}
    55  	}
    56  	g.Add(&makr.Func{
    57  		Should: func(data makr.Data) bool { return true },
    58  		Runner: func(root string, data makr.Data) error {
    59  			return generators.AddInsideAppBlock(fmt.Sprintf("app.Resource(\"/%s\", %sResource{&buffalo.BaseResource{}})", data["resourceURL"], data["resourceName"]))
    60  		},
    61  	})
    62  
    63  	if !skipModel && useModel == "" {
    64  		g.Add(modelCommand(data))
    65  	}
    66  
    67  	return g, nil
    68  }
    69  
    70  func modelCommand(data makr.Data) makr.Command {
    71  	modelName := inflect.Underscore(data["modelSingularUnder"].(string))
    72  
    73  	args := data["args"].([]string)
    74  	args = append(args[:0], args[0+1:]...)
    75  	args = append([]string{"db", "g", "model", modelName}, args...)
    76  
    77  	if skipMigration := data["skipMigration"].(bool); skipMigration {
    78  		args = append(args, "--skip-migration")
    79  	}
    80  
    81  	return makr.NewCommand(exec.Command("buffalo", args...))
    82  }