Skip to content

Instantly share code, notes, and snippets.

@54chi
Last active January 30, 2017 09:03
Show Gist options
  • Save 54chi/860c237c42d65f88418cfdc0c15cafb2 to your computer and use it in GitHub Desktop.
Save 54chi/860c237c42d65f88418cfdc0c15cafb2 to your computer and use it in GitHub Desktop.
Quicksheet for Vagrant/Postgres/Elixir/Phoenix for my repos

#PHOENIX IN CLOUD9

##Every now and then "maintenance":

Depending on how acitve you are, your Cloud 9 virtual instance may go to sleep from time to time. When this happens, couple things will go down with it too. Fret not, here is how to put them all back again:

  1. Reinitialize the environment(system) variables. In the console, make sure you are in the folder that holds your ".env" file and type: source .env. You can then check your system variables with the following console command: printenv
  2. You may also need to restart the DB service (if you installed on the same instance). For Postgresql, type the following in the console to do so: sudo service postgresql start

To sum up:

  source .env
  sudo service postgresql start

##After creating any new project (or cloning one):

By default, Cloud9 blocks port 4000, so you'll need to change it (e.g. to port 8080). There is also a problem with the default encoding (UTF8 vs SQL_ASCII), but that can be fixed by changing the db "template" line (if you are using Postgresql).

In other words, make these changes in your config files (e.g. config/dev.exs):

  # Configure your endpoint
  config :what, What.Endpoint,
    http: [port: 8080],
    debug_errors: true,
    ...
  # Configure your database
  config :what, What.Repo,
    adapter: Ecto.Adapters.Postgres,
    ...
    template: “template0”,
    ...

##Cloud 9 Setup:

The original guide was made by Andres Perez and is here

  1. Install all dependencies:
  sudo touch /etc/init.d/couchdb
  wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb
  sudo dpkg -i erlang-solutions_1.0_all.deb
  sudo apt-get update
  sudo apt-get install -y elixir
  mix local.hex
  sudo apt-get install -y erlang
  nvm install stable
  nvm alias default stable
  sudo apt-get install -y erlang-base-hipe erlang-dev erlang-eunit erlang-parsetools
  mix archive.install https://github.com/phoenixframework/archives/raw/master/phoenix_new.ez
  sudo apt-get install -y inotify-tools
  1. Start the Postgres DB service: sudo service postgresql start
  2. Change the Postgres password if needed: sudo -u postgres psql
  3. That's it. You are ready to go.

#PHOENIX IN VAGRANT

The github vagrant project will take care of spawning a phoenix machine, but there are a few extra things to consider: Vagrant sync is not very good yet, especially on Windows machines. I work around this problem with 2 terminal windows:

  1. One for your main coding
  2. Another one for they sync between your vm and your local drive

##Main terminal console

  1. vagrant up to initialize a Vagrant machine
  2. vagrant ssh to SSH into the Vagrant box (which you may need to do often)
  3. cd to "/vagrant/projects/" and from here do all your phoenix/elixir stuff

##Secondary Window (for synch):

After vagrant is up on the main terminal, you have a couple options:

  • If you want to synchronize from the host (your hard disk) to the guest (the vm), do this: vagrant rsync-auto
  • And/or if you want to synchronize from the guest to the host, do this: vagrant rsync-back <-- you may need to install this plugin

##Other useful stuff:

In case you want to have a nice colored syntax in your Vagrant's vim:

  1. Install pathogen.vim in the Vagrant machine: https://github.com/tpope/vim-pathogen
  2. Install the elixir-lang plugin for vim: https://github.com/elixir-lang/vim-elixir

#Environment files

Environment files will help you keep your sensitive information (e.g. API keys, passwords, URLs, etc.) safe from ending up in your github repo by mistake :p. Both Cloud9 and Vagrant support them.

To use them, just create a file with any name (e.g. I like the name them ".env") and set your system variables in it.

E.g. of my ".env"

  export mailgun_API_Base_URL="https://api.mailgun.net/v3/xxxxxxx.com"
  export mailgun_API_Key="key-xxxxxxxxxxx"

Once this is done, to update your system variables all you need to do is run this in the console: source .env

And here is how you can call these variables in your Elixir/Phoenix app: System.get_env() E.g. (in your config file):

  
    # Configure mailgun
    config :myApp,
      mailgun_domain: String.rstrip(System.get_env("mailgun_API_Base_URL")),
      mailgun_key:    String.rstrip(System.get_env("mailgun_API_Key")),
      ...

Obviously, make sure to udpate your ".gitignore" file to ignore this file (e.g. ".env").

####One more thing:

Maybe because I use Windows to write the .env file, and/or because I'm dumb, I need to add "String.rstrip()" because otherwise I would also get the carriage return code being added to the end of the variables when retrieving them :p.

Cheatsheet of sorts:

SYSTEM ENVIRONMENT reference:

  1. Load the system environment variables source .env (you should keep one of these files in your vagrant folder. They are super useful!)
  2. View the system environment variables: printenv

POSTGRESQL reference:

  1. Before using psql console, you will need to switch to the postgres user: sudo -u postgres -i
  2. Psql basic stuff:
  • Load Postgres console: psql
  • List databases: \list
  • "Use" a database: \connect
  • View tables and relations: \d
  • View table structure details: \d
  • Exit Postgres console: \q
  1. Exit Postgres user and get back to Vagrant's: exit

ELIXIR, ECTO AND PHOENIX reference:

  1. Test your stuff: mix tests
  2. ECTO:
  3. Create a database: mix ecto.create (based on the /config settings)
  4. Create a model: Use phoenix.gen.model E.g.mix phoenix.gen.model User users first_name:string last_name:string email:string encrypted_password:string
  5. Add "uniqueness index" in the migration file created above. E.g.create unique_index(:users, [:email])
  6. Add any validation inside the changeset defintion of your model file. E.g. in the user model created above:
```
def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> validate_format(:email, ~r/@/)
    |> validate_length(:password, min: 5)
    |> unique_constraint(:email, message: "Email already taken")
```
  1. Run the migrations: mix ecto.migrate

  2. Create additional migration files: Use ecto.gen.migration. E.g. mix ecto.gen.migration add_role_id_to_users

  3. Creating relationships within models: 1. Update the created migration file (def change). E.g. create a one-to-many relationship between roles and users in the file generated above.

      def change do alter table(:users) do 
        add :role_id, references(:roles) 
      end 
      
      create index(:users, [:role_id]) end
    
2. Update the relationship in the model: 
  1. Open the user model and add the association under the users' schema: `belongs_to :roles, .Role`
  2. And in the roles model: `has_many :users, .User`
3. Also update the Role controller. More info [here](https://medium.com/@diamondgfx/writing-a-blog-engine-in-phoenix-part-2-authorization-814c06fa7c0#.xqpnx52ic)
  1. Run the migrations:mix ecto.migrate
  2. Start the web server: mix phoenix.server
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment