github.com/jacobsoderblom/buffalo@v0.11.0/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/pkg/errors"
    10  
    11  	"github.com/gobuffalo/buffalo/generators"
    12  	"github.com/gobuffalo/makr"
    13  	"github.com/gobuffalo/packr"
    14  )
    15  
    16  // Run generates a new actions/resource file and a stub test.
    17  func (res Generator) Run(root string, data makr.Data) error {
    18  	g := makr.New()
    19  	defer g.Fmt(root)
    20  
    21  	data["opts"] = res
    22  	data["actions"] = []string{"List", "Show", "New", "Create", "Edit", "Update", "Destroy"}
    23  
    24  	tmplName := "resource-use_model"
    25  
    26  	if res.SkipModel {
    27  		tmplName = "resource-name"
    28  	}
    29  
    30  	files, err := generators.FindByBox(packr.NewBox("../resource/templates"))
    31  	if err != nil {
    32  		return errors.WithStack(err)
    33  	}
    34  
    35  	for _, f := range files {
    36  		// Adding the resource template to the generator
    37  		if strings.Contains(f.WritePath, tmplName) {
    38  			folder := res.FilesPath
    39  			if strings.Contains(f.WritePath, "actions") {
    40  				folder = res.ActionsPath
    41  			}
    42  			p := strings.Replace(f.WritePath, tmplName, folder, -1)
    43  			g.Add(makr.NewFile(p, f.Body))
    44  		}
    45  		if !res.SkipTemplates {
    46  			// Adding the html templates to the generator
    47  			if strings.Contains(f.WritePath, "model-view-") {
    48  				targetPath := filepath.Join(
    49  					filepath.Dir(f.WritePath),
    50  					res.FilesPath,
    51  					strings.Replace(filepath.Base(f.WritePath), "model-view-", "", -1),
    52  				)
    53  				g.Add(makr.NewFile(targetPath, f.Body))
    54  			}
    55  		}
    56  	}
    57  	g.Add(&makr.Func{
    58  		Should: func(data makr.Data) bool { return true },
    59  		Runner: func(root string, data makr.Data) error {
    60  			return generators.AddInsideAppBlock(fmt.Sprintf("app.Resource(\"/%s\", %sResource{})", res.Name.URL(), res.Name.Resource()))
    61  		},
    62  	})
    63  
    64  	if !res.SkipModel && !res.UseModel {
    65  		g.Add(res.modelCommand())
    66  	}
    67  
    68  	return g.Run(root, data)
    69  }
    70  
    71  func (res Generator) modelCommand() makr.Command {
    72  	args := res.Args
    73  	args = append(args[:0], args[0+1:]...)
    74  	args = append([]string{"db", "g", "model", res.Model.UnderSingular()}, args...)
    75  
    76  	if res.SkipMigration {
    77  		args = append(args, "--skip-migration")
    78  	}
    79  
    80  	return makr.NewCommand(exec.Command("buffalo", args...))
    81  }