roryfahy

roryfahy

Hey @kenny-evitt would you by any chance have an example script you could share of how to go about this?

1
Post #11
kenny-evitt

kenny-evitt

I can’t share the examples as-is but I can share examples that I think convey the gist.

I have a Mix alias in mix.exs like this:

  defp aliases do

      ...

      "ecto.setup": [
        ...
        "run priv/repo/seeds.exs"
      ],

      ...

You could also run the seeds script by itself:

$ mix run priv/repo/seeds.exs

My priv/repo/seeds.exs file looks like:

Code.eval_file("priv/repo/seed/something.exs")

Code.eval_file("priv/repo/seed/something-else.exs")

...

But it’s totally reasonable to just start with everything in one file.

priv/repo/seed/something.exs would look like:

something_1 =
  %MyApp.Something{
    name: "Blah blah blah",
    ...
  }
  |> Repo.insert!()

...

Note that you can access your app’s code, so you can, e.g. call ‘regular’ functions in your app’s modules or its dependencies or extract code or data into new modules:

password = RepoSeedsInfo.password()

user_1_email = RepoSeedsInfo.user_1_email()

something_1 =
  MyApp.User.changeset(
    %MyApp.User{},
    %{
      email:    user_1_email,
      password: password
    }
  )
  |> Repo.insert!()

My main use case is for populating :dev and :test DBs but you could split up or organize your code to handle whatever else you want.

0
Post #12
roryfahy

roryfahy

Thank you @kenny-evitt. How do you handle wanting to generate a lot of Something? or do you not often find yourself needing larger samples to operate on?

1
Post #13
kenny-evitt

kenny-evitt

You’re welcome!

Pragmatically, I’ve mostly been slowly accumulating seed data for specific purposes, so I’ve mostly been adding small ‘bespoke’ samples.

Generating larger samples is, in general, arbitrarily hard (or can be), e.g. ‘mimicking production’.

But again, in practice, it’s been easy enough to write a function like MyApp.Test.AThing.random_thing/x if you do need lots of seed items. I’ve found lots of shared uses between code like that that’s useful for tests and generating seed data. This has mostly been helpful for, e.g. testing UI lists or bounds/filters of complex DB queries, and not (much at all) for ‘simulating production’.

0
Post #14
— All posts loaded —