PART 2 | PART 3 | PART 4 | NOTES | SHARE YOUR PROJECT
A bucket list for things to do in Los Angeles.
If you moved out of Los Angeles next month what are the places you wished you went to and the things you wish you did. Make a list of cool things to do so you can make a plan to do them in case you move someday. You don't want to have any regrets.
At the end of the day you should
- Feel comfortable in the terminal
- Have your project online
- Be comfortable in git
- Meet new friends to learn with
- Find a mentor
- Get resources to continue learning
- Have Fun! <3
You should know
- about ERB (Embeded Ruby) and how to use it
- how to start a new Rails project
- the difference between your local and remote code
- what MVC means
- what C.R.U.D. stands for and what it means
- some markdown
- about testing
- how to add a gem to your project
- about our friend Bundler
https://gist.github.com/jendiamond/5a26b531e8e47b4aa638#file-tutorial_sharing-md
- Be kind to yourself. You are not less than anyone else because you do not know something.
- Be considerate. Remember that all the coaches and organizers are happily volunteering their time to help you.
- Respect others. Remember your coach is having patience with you so have patience with your student pair.
If you have any problems with anyone please let someone know. Code of Conduct
Go over the commandline prompts with your coach so you can be sure you can communicate clearly and easily throught the day.
- See what directory you are currently in
pwd
- Navigate to the Desktop directory
cd
- Create a new directory called rainbow
mkdir rainbow
- Change into the rainbow directory
cd rainbow
- Create a new directory in the rainbow directory called leprechaun
mkdir leprechaun
- Change into the leprechaun directory
cd leprechaun
- Create 3 files gold.md, nyancat.md & unicorn.md (in the terminal)
touch gold.md nyancat.md unicorn.md
- List the files in the leprechaun directory
ls
- Go into sublime and add a bit of text to the gold.md file
subl .
- Open the file in the terminal and read it
cat gold.md
- Delete the gold.md file from the leprechaun directory
rm gold.md
- Change back into the rainbow directory
cd ../
- Delete the rainbow directory
rm -r rainbow
- Find the flag to list all the hidden files
man ls
(ls -a
)
Hooray for The Terminal Slide Show!
Psst - If you ever see a $
sign in this tutorial, it is not part of the code. The $
sign means that you should type the code that follows it into your terminal.
In the first section we are going to do a small amount of code but we will learn a lot about it.
Open a terminal and create a new directory and navigate into that directory.
$ mkdir railsgirls
$ cd railsgirls
Verify that your directory is currently empty. ls -a
and instead of running this:
$ rails new la_adventures
You could run this:
$ rails new la_adventures -d postgresql
MAC: https://www.robinwieruch.de/postgres-sql-macos-setup
https://postgresapp.com/
https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-ruby-on-rails-application-on-macos
Windows: https://www.postgresql.org/download/windows/
https://www.postgresqltutorial.com/install-postgresql/
https://www.guru99.com/download-install-postgresql.html
Generate a new rails app called la_adventures
by running:
This will set up your project with a SQLlite database
$ rails new la_adventures
This will create a new app in the la_adventures
folder/directory.
Change into the la_adventures directory to get inside of our rails app.
$ cd la_adventures
Look at all the stuff you got from typing 3 small words. Check it out in your text editor.
The chart below is from the Railsbridge Intro to Rails tutorial
File/Folder | Purpose |
---|---|
app/ | Contains the controllers, models, and views for your application. You will do most of your work here. |
config/ | Configure your application's runtime rules, routes, database, and more. |
db/ | Shows your current database schema, as well as the database migrations. |
public/ | The only folder seen to the world as-is. If you put files in here, they will be served directly without any processing by Rails. |
app/assets/ | This is where your images, JavaScript, stylesheets (CSS), and other static files should go. Modern Rails apps use something called the Assets Pipeline, which combines all the JavaScript and CSS files in this directory into a single file for speediness. |
Start the rails server to see your new app by running:
$ rails server
- rails server or rails s starts our local server in our terminal
- ctrl+c shuts down our server if its active
- ctrl+l clears the terminal screen. "clear" itself also works, unless we're in the rails command-line.
Open http://localhost:3000 in your browser.
You should see “Welcome aboard” page, which means that the generation of your new app worked correctly.
You may want to run a second terminal to have the rails server run continuously.
The WEBrick server. This is so you can see what your app will look like in production on the web. Notice that each time you add a new adventure or do anything inyour web site the server in your terminal shows a bunch of new stuff. If you look at it you can see what it is doing relates to what you are doing on the site. You should see something like this below:
=> Booting WEBrick
=> Rails 4.2.0 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
When you are running the Rails server you cannot execute new commands.
If you try running cd
or another command it will not work.
To return to the normal command prompt:
Type
CTRL-C
in the terminal to quit the server.
Before we do anything else lets create a local repository and save our new project to it. We will use a workflow for git that follows along these lines each time we commit. Hooray for TryGit!
$ git init
git status
git add .
git status
git commit -m 'Initial commit'
git status
This chart shows what each command means. This is your git workflow. Which means EVERY TIME we ask you to commit to git and GitHub in this tutorial you should follow these steps. It is a good habit to follow all these steps.
Your Git Workflow | :) |
---|---|
git status |
Check status |
git add . |
Add everything to the repository |
git status |
Check status |
git commit -m 'Your comment' |
Commit everything (-m means message) |
git status |
Check status* |
Again I will say, every time you commit, follow these steps. It's good practice and it will help you from getting messed up when things get more complex.
Where it says Your comment this is where you write in what you commit contains. It should note what you did. These comments are meant for you to remember what you did so make them very meaningful.
They are also public for everyone to read for ever. ;) A Note About Git Commit Messages
Pushing to GitHub | :) |
---|---|
Create a Github repository | https://github.com |
Add the remote host to your local git | git remote add origin [email protected]:your_username/your_repository_name |
Check your remotes | git remote -v |
Push commit to Github | git push -u origin master |
Coach: Discuss you git workflow.
https://youtu.be/IsvfofcIE1Q https://youtu.be/xnKhsTXoKCI
For the rest of the project you will only need to use the command git push origin master
to push your changes to GitHub.
We are going to use a DSL called Markdown to write our README file.
Look on GitHub at your current README File.
Note that it is a file in the list with all your other files but it is also shown at the bottom of your page so everyone can read it.
Markdown Documentation
First of all what is a DSL? - This is an acronym for Domain Specific Language. A DSL is a mini-language based on another. (Like Pig Latin.) A DSL uses a base language and abstracts it to have a particular functionality or make it simpler to write.
If you are in an earlier version of Rails change the name of the README file from README.rdoc
to README.md
Open the README.md
in your text editor. This is now a markdown file. The .md
suffix is for markdown.
This guide is written in markdown. :) Markdown is a way to write HTML in a stripped down way.
Checkout Daring Fireball to learn more on how to use Markdown. (The Daring Fireball site is by John Gruber who wrote Markdown.)
## Rails Girls 2015
---
#### Ruby version 2.3.0
#### Rails version 5.0.0.1
### L.A. Adventure App
A bucket list for Los Angeles. This is a list of all the things I'd like to do in case I moved out of Los Angeles and never got to return. All the things I think about doing all the time but haven't made time to do yet.
*Made by* **Your Name**
On 10-22-2016
My Coach: (your coach's name)
My Pair: (your coach's name)
Commit from your home directory wherever you put it. Mine is here:
$Desktop/railsgirls/la_adventures
Do each of these commands one at a time...
git status
git add .
git status
git commit -m 'Update the README'
git status
git push origin master
Coach:
- Show your students how to use Markdown on the commit you just pushed on GitHub.
- Show how to create a gist in Github. You could put your notes for the day on a gist. More info.about Gists from GitHub.
- Show your students some other README files from other GitHub repositories
RSpec
Bundler
We’re going to use Rails’ scaffold functionality to generate a starting point that allows us to list, add, remove, edit, and view things.
In our case the scaffold and C.R.U.D. will let us:
- Create a New Adventures (new / create)
- Read about our Adventures (show) - List all our adventures (index)
- Update / Edit our Adventures (edit / update
- Delete our Adventures (destroy)
In Rails we call it C.R.U.D., the acronym for
Create
Read
Update
Destroy
Adventures Table
id | name | description | picture | location | visit
---------------|-----------|---------------|----------------------------|--------------|--------------
auto-generated | string | text | string | string | date
1 | "zoo" | "Animals!" |"http://tinyurl.com/zfq77mm"| 5333 Zoo Dr. | "2016-03-26"
Let's just peek in app/model
Note that there is no model there yet.
After we run the next command there will be an Adventure model. app/models/adventure.rb
( You can also peek at app/controllers
and app/views
.)
$ rails generate scaffold adventure name:string description:text picture:string location:string visit:date
The scaffold creates new files in your project directory, but to get it to work properly we need to run a couple of other commands to update and create our Adventure database.
Active Record is the M in MVC It facilitates the use of your database.
Active Record uses some naming conventions.
Rails will pluralize your class names to find the respective database table.
So, for a class Adventure, you should have a database table called Adventure.
Note: You can run $ rails generate scaffold
with no model name to get info and examples of a rails scaffold.
rake db:migrate
Open the db/migrate/(date_time)_create_adventures.rb
file. (Psst - (date_time)
will be different in every app)
Notice that all the things that we just typed to create the scaffold are here in this file:
class CreateAdventures < ActiveRecord::Migration
def change
create_table :adventures do |t|
t.string :name
t.text :description
t.string :picture
t.string :location
t.date :visit
t.timestamps null: false
end
end
end
Let us also peek in the db
directory.
The file that the database table will be in is called schema.db
Note that there is no schema.db
there yet.
Once we run rake db:migrate
it will be created from the migration file.
db/migrate/(date_time)_create_adventures.rb
rake db:migrate
Note: In Rails 5 you can run $
rails db:migrate
Restart your server and check out your app. (You have to restart your server when you run rake db:migrate)
Open http://localhost:3000/adventures in your browser.
rails server
(For now your image will only be a string. We will make it an image later in the guide.)
Play around with your new app.
- Create some new adventures.
- Delete some.
- List them all.
- Create some more.
- See what the C.R.U.D. is all about.
Started GET "/adventures/2" for 33.33.33.1 at 2016-02-26 01:48:33 +0000
Cannot render console from 33.33.33.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by AdventuresController#show as HTML
Parameters: {"id"=>"2"}
Adventure Load (3.1ms) SELECT "adventures".* FROM "adventures" WHERE "adventures"."id" = ? LIMIT 1 [["id", 2]]
Rendered adventures/show.html.erb within layouts/application (4.0ms)
Completed 200 OK in 109ms (Views: 103.0ms | ActiveRecord: 3.1ms)
- Rails scaffolding
Rails scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.
http://stackoverflow.com/questions/6735468/why-do-ruby-on-rails-professionals-not-use-scaffolding - What exactly is happening in the command
rails generate scaffold adventure name:string description:text picture:string visit:date
- MVC Model View Controller Model (ActiveRecord ) It maintains the relationship between the objects and the database and handles validation, association, transactions, and more.
This subsystem is implemented in ActiveRecord library, which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.
View ( ActionView ) It is a presentation of data in a particular format like html or json, triggered by a controller's decision to present the data.
This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation.
Controller ( ActionController ) The facility within the application that directs traffic, like, querying the models for specific data, or, organizing that data (searching, sorting, messaging it) into a form that fits the needs of a given view.
This subsystem is implemented in ActionController, which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).
- Look at the model name and related database table and the controller for it
- Naming conventions - singular in the model - plural in the controller - CapitalizedCamelCase Classes
- What are migrations and why do you need them?
- What is Rake?
All of our adventures are stored in our database. This is where we get into the MVC or the Model View Controller aspect of our application.
The following explanation is from the Railsbridge Intro to Rails tutorial
(Psst -You should try this tutorial on your own after this workshop. It is excellent! Sarah Mei and Sara Allen are responsible for creating Rails Bridge which inspired the creation of Rails Girls which is why you are here today. If you ever meet these women shake their hand vigorously and thank them.)
Also you should know the names Linda Liukas and Karri Saarinen who founded Rails Girls and are awesome! :)
This file contains code for our adventure model. If you look at it, it's nearly blank. Creating, reading, updating, and deleting records are built into Rails.
This folder contains all the views for our adventures model. This is where the code for the forms you used above is stored. Rails created all of these pages as part of the scaffold. If you've written HTML before, many lines in the views should look familiar. Rails views are HTML with some extra code added to display data from the database. Yay Dash tutorial!
This is the code for the page that lists all the adventures. Index is the name given to the "default" page for a web site or a section of a web site. When you navigate to http://localhost:3000/adventures the adventures index page is what is sent to your computer.
This is the page you get when you click the "Show" link on the "Listing adventures" page.
This is the page you get when you click "New Adventure".
This is the page you get when you click "Edit".
You may have noticed that the page for new adventures and the page to edit adventures looked similar. That's because they both use the code from this file to show a form. This file is called a partial since it only contains code for part of a page. Partials always have filenames starting with an underscore character.
Challenge question: Can you find the line of code in new.html.erb and edit.html.erb that makes the form partial appear?
This is the controller file that Rails created as part of the scaffold If you look you'll see a method (a line beginning with def) for each of the views listed above (except _form.html.erb)
You may have noticed that the first page of your application still shows the “Welcome aboard” page. Let’s make it go straight to the Adventures page.
Open config/routes.rb
and after the first line add
root 'adventures#index'
Test the change by opening the root path http://localhost:3000 in your browser.
Rails routing configurations are kept in config/routes.rb file.
http://guides.rubyonrails.org/routing.html
- When your Rails application receives an incoming request for:
GET /adventures/17
- In the form of a URL, for us right now it is http://localhost:3000//adventures/17
GET /adventures/17
asks the router to match it to a controller action.- Our router reads:
resources :adventures
This includes all the CRUD actions
Create Read Update Destroy - The request is dispatched to the adventures controller's show action with { id: '17' } in params.
adventures_controller.rb
def show
@adventure = Adventure.find(params[:id])
end
The code above defines the method show
, a.k.a the controller action show
,
- it assigns the instance variable
@adventure
to the adventure which is in the url - so if we were at http://localhost:300/adventures/3
- then we would view the page for the adventure with the id of 3
Look at the `rake routes below:
adventure | GET| /adventures/:id(.:format) | adventures#show
Browsers request pages from Rails by making a request for a URL using a specific HTTP method, such as GET, POST, PATCH, PUT and DELETE. Each method is a request to perform an operation on the resource. A resource route maps a number of related requests to actions in a single controller.
Coach: Run $ rake routes
, and discuss it a bit.
Prefix | Verb | URI Pattern | Controller#Action |
---|
root | GET | / | adventures#index
adventures | GET | /adventures(.:format) | adventures#index
| POST | /adventures(.:format) | adventures#create
new_adventure | GET | /adventures/new(.:format) | adventures#new
edit_adventure | GET | /adventures/:id/edit(.:format) | adventures#edit
adventure | GET| /adventures/:id(.:format) | adventures#show
| PATCH | /adventures/:id(.:format) | adventures#update
| PUT | /adventures/:id(.:format) | adventures#update
| DELETE | /adventures/:id(.:format) | adventures#destroy
http://guides.railsgirls.com/heroku
We are now going to put our app on the internet.
First you have to
Run your git workflow again to commit all changes.
Your message this time should be 'Add Adventure scaffold, Update routes to show Adventure on home page'
Because we are going to deploy our app to Heroku we need to update our Gemfile.
Why? Well, because we are using a Sqlite3 database and Heroku uses a Postgres database.
That's completely alright.
The Sqlite3 database easily transfers to the postgress data bases.
Luckily Rails has multiple environments Development, Production and Test.
- The Development environment is where you develop your app.
- The Production environment is what you "push to production" / Heroku or whatever server you use.
- The Test environment is for testing.
Before we push to Heroku we need to do two things
- Move Sqlite3 into the production environment
- Add Postres to the production environment
The third thing you need to do if you are not in Rails 5 3. Add the Rails 12 factor gem to the Gemfile
We are going do two of our tasks
to move it into the development environment.
Then we are going to have the production environment use postgres.
(Heroku uses postres which is why we are adding it.)
There may be other gems in your production or development groups. That is okay.
There will also be a lot of comments. You can keep them or delete the. It's up to you. They are interesting to read.
Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 5.0.0', '>= 5.0.0.1'
gem 'sqlite3'
gem 'puma', '~> 3.0'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'carrierwave', '~> 0.10.0'
gem 'jquery-rails'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
group :development, :test do
gem 'byebug', platform: :mri
end
group :development do
gem 'web-console'
gem 'listen', '~> 3.0.5'
gem 'spring'
gem 'spring-watcher-listen', '~> 2.0.0'
end
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
===
Add: `ruby '2.3.0'
===
- development - This is where you develop your code
- production - This is the code you push to a server like Heroku
- test - This is where you test your code
===
- Move Sqlite3 into the production environment
gem 'sqlite3'
- Add Postres to the production environment
gem 'pg'
to move it into the development environment.
We are going to have the production environment use PostgresSQL which is a database.
Heroku uses Postres which is why we are adding it. If you don't add it,
===
group :production do
gem 'pg'
end
So your Gemfile looks like this:
source 'https://rubygems.org'
gem 'rails', '4.2.5'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
group :development, :test do
gem 'byebug'
end
group :development do
gem 'web-console', '~> 2.0'
gem 'spring'
gem 'sqlite3'
end
group :production do
gem 'pg'
end
Notice the words do
and end
means this is a block of code that belongs together.
All the gems you want to be ONLY in the development
group need to be in between the do
and end
of the development
block.
There are other gems that are outside of these groups. That is okay too. They are available to all the groups.
More about groups by Yahuda Katz.
$ bundle install --without production
Coach: - Discuss why you run bundle install and what the Gemfile.lock is doing.
If heroku is not running you may need to install the heroku toolbelt.
===
This gem was incorporated into Rails 5 so you don't need it. Unless you are converting a Rails 4 app to Rails 5.
The Rails_12factor gem makes our app available on Heroku.
This gem modifies the way Rails works to suit Heroku, for example Logging is updated and the configuration for static assets (your images, stylesheets and javascript files) is tweaked to work properly within Heroku’s systems.
https://github.com/heroku/rails_12factor/blob/master/README.md
heroku/rails_12factor#3
Please change the following in the Gemfile:
group :production do
gem 'pg'
end
to
group :production do
gem 'pg'
gem 'rails_12factor'
end
Then run bundle install
in your terminal.
$ bundle
Your Gemfile should now look like this:
source 'https://rubygems.org'
gem 'rails', '4.2.5'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
group :development, :test do
gem 'byebug'
end
group :development do
gem 'web-console', '~> 2.0'
gem 'spring'
end
group :production do
gem 'pg'
gem 'rails_12factor'
end
Your comment should be 'Add Postgres'
===
To get more information on why this change is needed and how to configure your app to run Postgres locally, see why you cannot use Sqlite3 on Heroku.
===
Read this all first and discuss it and then we'll do these two commands.
In your terminal type:
heroku create
Then type:
git push heroku master
We need to create our Heroku app by typing heroku create
in the terminal and see something like this:
Creating sheltered-refuge-6377... done, stack is cedar
http://sheltered-refuge-6377.herokuapp.com/ | [email protected]:sheltered-refuge-6377.git
Git remote heroku added
In this case “sheltered-refuge-6377” is your app name.
Next we need to push our code to heroku by typing git push heroku master
. You’ll see push output like the following:
Initializing repository, done.
Counting objects: 101, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (91/91), done.
Writing objects: 100% (101/101), 22.68 KiB | 0 bytes/s, done.
Total 101 (delta 6), reused 0 (delta 0)
-----> Ruby app detected
-----> Compiling Ruby/Rails
-----> Using Ruby version: ruby-2.0.0
-----> Installing dependencies using 1.6.3
Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
Fetching gem metadata from https://rubygems.org/..........
...
-----> Launching... done, v6
http://sheltered-refuge-6377.herokuapp.com/ deployed to Heroku
You’ll know the app is done being pushed, when you see the “Launching…” text like above.
Next we need to migrate our database like we did locally:
$ heroku run rake db:migrate
===
In a browser got to http://sheltered-refuge-6377.herokuapp.com/ (except put the name of your app in there instead of sheltered-refuge-6377.)
Heroku’s platform is not without its quirks. Applications run on Heroku live within an ephermeral environment — this means that (except for information stored in your database) any files created by your application will disappear if it restarts which is why it takes so long to spin up when you first go to the site.
Obviously this doesn’t seem to be useful if you were running a real life application, but there are ways to work around this which is commonly used by a lot of popular websites.
Stretch.
Walk around the block.
Notice that there are other people in the room.
Don't skip taking breaks and being away from the computer.
Regular breaks allow you to go longer and learn more.
Shanah Zilberkweit
Email: [email protected]
@shanahz
My coach: Joshua Loper
My pair: Lindsay St John
My website: https://railsgirlsberlin.herokuapp.com/
Thank you for organizing such a great event! ✨ 💻 💡