From 27b02ad04aeb60844a1deb6676d3bb812abb041c Mon Sep 17 00:00:00 2001 From: hrushikeshj Date: Fri, 13 Jan 2023 16:26:39 +0530 Subject: [PATCH 01/13] Add week 3 tests --- .github/workflows/week3_intro.yml | 2 +- .github/workflows/week3_model.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/week3_intro.yml b/.github/workflows/week3_intro.yml index 3acdee3c..11b2c77b 100644 --- a/.github/workflows/week3_intro.yml +++ b/.github/workflows/week3_intro.yml @@ -9,7 +9,7 @@ on: workflow_dispatch: jobs: - week2: + week3: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/week3_model.yml b/.github/workflows/week3_model.yml index 2ac537ac..c940d1a1 100644 --- a/.github/workflows/week3_model.yml +++ b/.github/workflows/week3_model.yml @@ -9,7 +9,7 @@ on: workflow_dispatch: jobs: - week2: + week3_model: runs-on: ubuntu-latest steps: From 5c5a1cd908310b14c9244a02ce8ad521376d75bb Mon Sep 17 00:00:00 2001 From: hrushikeshj Date: Fri, 13 Jan 2023 16:39:31 +0530 Subject: [PATCH 02/13] Add week 3 tests --- .github/workflows/week3_intro.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/week3_intro.yml b/.github/workflows/week3_intro.yml index 11b2c77b..2ac63e1d 100644 --- a/.github/workflows/week3_intro.yml +++ b/.github/workflows/week3_intro.yml @@ -21,7 +21,6 @@ jobs: with: ruby-version: 3.0.5 working-directory: week_3/hello_world - bundler-cache: true - name: Install NPM packages uses: bahmutov/npm-install@v1 From 77ab65bc5afb6205139643bc8a0ec9b599d55319 Mon Sep 17 00:00:00 2001 From: hrushikeshj Date: Fri, 13 Jan 2023 16:44:28 +0530 Subject: [PATCH 03/13] Add week 3 tests --- .github/workflows/week3_intro.yml | 2 +- .github/workflows/week3_model.yml | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/week3_intro.yml b/.github/workflows/week3_intro.yml index 2ac63e1d..a44c45c6 100644 --- a/.github/workflows/week3_intro.yml +++ b/.github/workflows/week3_intro.yml @@ -19,8 +19,8 @@ jobs: - name: Install Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: 3.0.5 working-directory: week_3/hello_world + bundler-cache: true - name: Install NPM packages uses: bahmutov/npm-install@v1 diff --git a/.github/workflows/week3_model.yml b/.github/workflows/week3_model.yml index c940d1a1..8eb8b058 100644 --- a/.github/workflows/week3_model.yml +++ b/.github/workflows/week3_model.yml @@ -19,7 +19,6 @@ jobs: - name: Install Ruby uses: ruby/setup-ruby@v1 with: - ruby-version: 3.0.5 working-directory: week_3/football bundler-cache: true From 221d1cd2f946de782dbd21e912a72d2091a1c647 Mon Sep 17 00:00:00 2001 From: Hrushikesh <66632353+hrushikeshj@users.noreply.github.com> Date: Fri, 13 Jan 2023 20:18:54 +0530 Subject: [PATCH 04/13] Update README.md --- week_3/football/README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/week_3/football/README.md b/week_3/football/README.md index 24e18349..b6e1a06c 100644 --- a/week_3/football/README.md +++ b/week_3/football/README.md @@ -216,3 +216,11 @@ FootballPlayer.find_by(name: "Messi").destroy - [DELETE | ActiveRecord](https://guides.rubyonrails.org/active_record_basics.html#delete) + +# Rails console +The Rails console is useful for testing out quick ideas with code and debugging applications. + +```bash +rails console +``` +![image](https://user-images.githubusercontent.com/66632353/212348259-fbf59057-7eb1-4e1a-af8c-634161164afc.png) From e31472201f100e16b37a7817760bce9a9822d5b0 Mon Sep 17 00:00:00 2001 From: Parth Mittal <76661350+mittal-parth@users.noreply.github.com> Date: Sat, 14 Jan 2023 00:04:57 +0530 Subject: [PATCH 05/13] Add creating tables for week-3 (#108) * add activity-tracker app * add readme and instructions * remove conflicting files --- week_3/README.md | 108 ++++---- week_3/activity-tracker/.ruby-version | 1 + week_3/activity-tracker/Gemfile | 72 ++++++ week_3/activity-tracker/Gemfile.lock | 232 ++++++++++++++++++ week_3/activity-tracker/README.md | 151 ++++++++++++ week_3/activity-tracker/Rakefile | 6 + .../app/assets/config/manifest.js | 4 + .../activity-tracker/app/assets/images/.keep | 0 .../app/assets/stylesheets/application.css | 15 ++ .../app/channels/application_cable/channel.rb | 4 + .../channels/application_cable/connection.rb | 4 + .../app/controllers/application_controller.rb | 2 + .../app/controllers/concerns/.keep | 0 .../app/helpers/application_helper.rb | 2 + .../app/javascript/application.js | 3 + .../app/javascript/controllers/application.js | 9 + .../controllers/hello_controller.js | 7 + .../app/javascript/controllers/index.js | 11 + .../app/jobs/application_job.rb | 7 + .../app/mailers/application_mailer.rb | 4 + .../app/models/application_record.rb | 3 + .../app/models/concerns/.keep | 0 .../app/views/layouts/application.html.erb | 16 ++ .../app/views/layouts/mailer.html.erb | 13 + .../app/views/layouts/mailer.text.erb | 1 + week_3/activity-tracker/bin/bundle | 114 +++++++++ week_3/activity-tracker/bin/importmap | 4 + week_3/activity-tracker/bin/rails | 4 + week_3/activity-tracker/bin/rake | 4 + week_3/activity-tracker/bin/setup | 33 +++ week_3/activity-tracker/config.ru | 6 + week_3/activity-tracker/config/application.rb | 22 ++ week_3/activity-tracker/config/boot.rb | 4 + week_3/activity-tracker/config/cable.yml | 10 + .../config/credentials.yml.enc | 1 + week_3/activity-tracker/config/database.yml | 25 ++ week_3/activity-tracker/config/environment.rb | 5 + .../config/environments/development.rb | 72 ++++++ .../config/environments/production.rb | 93 +++++++ .../config/environments/test.rb | 60 +++++ week_3/activity-tracker/config/importmap.rb | 7 + .../config/initializers/assets.rb | 12 + .../initializers/content_security_policy.rb | 25 ++ .../initializers/filter_parameter_logging.rb | 8 + .../config/initializers/inflections.rb | 16 ++ .../config/initializers/permissions_policy.rb | 11 + week_3/activity-tracker/config/locales/en.yml | 33 +++ week_3/activity-tracker/config/master.key | 1 + week_3/activity-tracker/config/puma.rb | 43 ++++ week_3/activity-tracker/config/routes.rb | 6 + week_3/activity-tracker/config/storage.yml | 34 +++ week_3/activity-tracker/db/seeds.rb | 7 + week_3/activity-tracker/lib/assets/.keep | 0 week_3/activity-tracker/lib/tasks/.keep | 0 week_3/activity-tracker/public/404.html | 67 +++++ week_3/activity-tracker/public/422.html | 67 +++++ week_3/activity-tracker/public/500.html | 66 +++++ .../public/apple-touch-icon-precomposed.png | 0 .../public/apple-touch-icon.png | 0 week_3/activity-tracker/public/favicon.ico | 0 week_3/activity-tracker/public/robots.txt | 1 + week_3/activity-tracker/storage/.keep | 0 .../test/application_system_test_case.rb | 5 + .../application_cable/connection_test.rb | 11 + .../activity-tracker/test/controllers/.keep | 0 .../test/fixtures/files/.keep | 0 week_3/activity-tracker/test/helpers/.keep | 0 .../activity-tracker/test/integration/.keep | 0 week_3/activity-tracker/test/mailers/.keep | 0 week_3/activity-tracker/test/models/.keep | 0 .../test/models/activity_model_test.rb | 23 ++ .../test/models/activity_test.rb | 7 + week_3/activity-tracker/test/system/.keep | 0 week_3/activity-tracker/test/test_helper.rb | 13 + week_3/activity-tracker/vendor/.keep | 0 .../activity-tracker/vendor/javascript/.keep | 0 week_3/getting_started_with_rails.md | 82 +++++++ 77 files changed, 1614 insertions(+), 63 deletions(-) create mode 100644 week_3/activity-tracker/.ruby-version create mode 100644 week_3/activity-tracker/Gemfile create mode 100644 week_3/activity-tracker/Gemfile.lock create mode 100644 week_3/activity-tracker/README.md create mode 100644 week_3/activity-tracker/Rakefile create mode 100644 week_3/activity-tracker/app/assets/config/manifest.js create mode 100644 week_3/activity-tracker/app/assets/images/.keep create mode 100644 week_3/activity-tracker/app/assets/stylesheets/application.css create mode 100644 week_3/activity-tracker/app/channels/application_cable/channel.rb create mode 100644 week_3/activity-tracker/app/channels/application_cable/connection.rb create mode 100644 week_3/activity-tracker/app/controllers/application_controller.rb create mode 100644 week_3/activity-tracker/app/controllers/concerns/.keep create mode 100644 week_3/activity-tracker/app/helpers/application_helper.rb create mode 100644 week_3/activity-tracker/app/javascript/application.js create mode 100644 week_3/activity-tracker/app/javascript/controllers/application.js create mode 100644 week_3/activity-tracker/app/javascript/controllers/hello_controller.js create mode 100644 week_3/activity-tracker/app/javascript/controllers/index.js create mode 100644 week_3/activity-tracker/app/jobs/application_job.rb create mode 100644 week_3/activity-tracker/app/mailers/application_mailer.rb create mode 100644 week_3/activity-tracker/app/models/application_record.rb create mode 100644 week_3/activity-tracker/app/models/concerns/.keep create mode 100644 week_3/activity-tracker/app/views/layouts/application.html.erb create mode 100644 week_3/activity-tracker/app/views/layouts/mailer.html.erb create mode 100644 week_3/activity-tracker/app/views/layouts/mailer.text.erb create mode 100755 week_3/activity-tracker/bin/bundle create mode 100755 week_3/activity-tracker/bin/importmap create mode 100755 week_3/activity-tracker/bin/rails create mode 100755 week_3/activity-tracker/bin/rake create mode 100755 week_3/activity-tracker/bin/setup create mode 100644 week_3/activity-tracker/config.ru create mode 100644 week_3/activity-tracker/config/application.rb create mode 100644 week_3/activity-tracker/config/boot.rb create mode 100644 week_3/activity-tracker/config/cable.yml create mode 100644 week_3/activity-tracker/config/credentials.yml.enc create mode 100644 week_3/activity-tracker/config/database.yml create mode 100644 week_3/activity-tracker/config/environment.rb create mode 100644 week_3/activity-tracker/config/environments/development.rb create mode 100644 week_3/activity-tracker/config/environments/production.rb create mode 100644 week_3/activity-tracker/config/environments/test.rb create mode 100644 week_3/activity-tracker/config/importmap.rb create mode 100644 week_3/activity-tracker/config/initializers/assets.rb create mode 100644 week_3/activity-tracker/config/initializers/content_security_policy.rb create mode 100644 week_3/activity-tracker/config/initializers/filter_parameter_logging.rb create mode 100644 week_3/activity-tracker/config/initializers/inflections.rb create mode 100644 week_3/activity-tracker/config/initializers/permissions_policy.rb create mode 100644 week_3/activity-tracker/config/locales/en.yml create mode 100644 week_3/activity-tracker/config/master.key create mode 100644 week_3/activity-tracker/config/puma.rb create mode 100644 week_3/activity-tracker/config/routes.rb create mode 100644 week_3/activity-tracker/config/storage.yml create mode 100644 week_3/activity-tracker/db/seeds.rb create mode 100644 week_3/activity-tracker/lib/assets/.keep create mode 100644 week_3/activity-tracker/lib/tasks/.keep create mode 100644 week_3/activity-tracker/public/404.html create mode 100644 week_3/activity-tracker/public/422.html create mode 100644 week_3/activity-tracker/public/500.html create mode 100644 week_3/activity-tracker/public/apple-touch-icon-precomposed.png create mode 100644 week_3/activity-tracker/public/apple-touch-icon.png create mode 100644 week_3/activity-tracker/public/favicon.ico create mode 100644 week_3/activity-tracker/public/robots.txt create mode 100644 week_3/activity-tracker/storage/.keep create mode 100644 week_3/activity-tracker/test/application_system_test_case.rb create mode 100644 week_3/activity-tracker/test/channels/application_cable/connection_test.rb create mode 100644 week_3/activity-tracker/test/controllers/.keep create mode 100644 week_3/activity-tracker/test/fixtures/files/.keep create mode 100644 week_3/activity-tracker/test/helpers/.keep create mode 100644 week_3/activity-tracker/test/integration/.keep create mode 100644 week_3/activity-tracker/test/mailers/.keep create mode 100644 week_3/activity-tracker/test/models/.keep create mode 100644 week_3/activity-tracker/test/models/activity_model_test.rb create mode 100644 week_3/activity-tracker/test/models/activity_test.rb create mode 100644 week_3/activity-tracker/test/system/.keep create mode 100644 week_3/activity-tracker/test/test_helper.rb create mode 100644 week_3/activity-tracker/vendor/.keep create mode 100644 week_3/activity-tracker/vendor/javascript/.keep create mode 100644 week_3/getting_started_with_rails.md diff --git a/week_3/README.md b/week_3/README.md index d7b18080..723706cd 100644 --- a/week_3/README.md +++ b/week_3/README.md @@ -1,90 +1,72 @@ -# Week 3 - Getting Started with Rails +# Week 3 - Getting Started with Rails + Models In this week we will get started with Rails. -We will create a simple rails app with two pages, a Home Page and an About Me page. +At first, we will create a simple rails app with two pages, a Home Page and an About Me page. -## Steps -- [Set Up Local Workplace](../setup/) +Follow [these](./getting_started_with_rails.md) instructions to get started. -- Create a new [gemset](../setup/README.md#RVM) and install rails -```bash -cd week_3 -rvm gemset create week_3 -rvm use 3.0.5@week_3 -gem install rails --version 7.0.4 -``` +# Models -- Create a new Rails project `hello_world` in the directory `week_1` -```bash -rails new hello_world --css=bootstrap --skip-git -cd hello_world -rvm use 3.0.5@week_3 -``` +We take a closer look at _Model_ of the MVC architecture and talk about +databases, migrations and working with records. -> The command `rails new` initialises a Rails project. We have passed -> the flag `--skip-git` to avoid initializing Git again as we are -> already within a Git repository. +The _model_ layer is responsible for storing and processing data. -- Run the rails server using below command and go to http://localhost:3000/. -```bash -rails server -``` +We store data in a _relational database_ and process it in the +`app/models` of the Rails application. -You should see the rails logo. +A _relational database_ stores information as a set of tables with columns +and rows (_records_). The tables and their columns are together called +a _schema_. You can think of relational database as a spreadsheet with +each table on a different sheet. -### Add a controller +> There are other non-tabular databases as well, which are better suited +> to specific problems: [What is a Database | Oracle](https://www.oracle.com/in/database/what-is-database/) -- Generate a new controller `PageController` with actions `root` and - `about_me`: +_Structured Query Language_ (SQL) is used to access and manipulate +databases. SQL can retrieve, create, read, update and destroy records, +modify schema and more. Working with SQL directly is difficult, so we +usually have a Rails equivalent. -```bash -rails generate controller Page root about_me -``` +The assignment is split into different sub-tasks, each testing a +different aspect of Model layer. -> A _controller_ is responsible for making sense of request and producing -> the appropriate output. It acts as a middleman between the Data -> (Model) and Presentation (View). Controllers are stored in -> `app/controllers` directory. +> We will be using SQLite as our database program, as it requires no +> setup and is Rails's default. -> The generator creates the files and fills it with some default code. -> the above command creates a controller -> `PagesController`, creates new view files `root.html.erb` and -> `about_me.html.erb` and modifies the routes file +## Task 1 - Creating Tables -- Edit the routes file (`config/routes.rb`) as follow to add new routes: +Relational databases stores information using tables. You can think of +tables and their columns as the format in which data is stored. -```ruby -Rails.application.routes.draw do - get '/', to: 'page#root' - get 'about_me', to: 'page#about_me' -end -``` +In this sub-task, we will build an activity tracker because as programmers we spend long hours sitting and need to keep track of our health. During the course of this bootcamp, we'll build the entire application, adding functionality each week. At the end, you'll have a fully functional acticity tracker! -The routes file specifies the URLs that are recognized by the application. +Head over to [activity-tracker](./activity-tracker/README.md) to learn more. -- Edit the view files `app/views/page/root.html.erb` and `app/views/page/about_me.html.erb`. +## Task 2 - Working with Records -- You should be able to see see your changes at `http://localhost:3000` and - `http://localhost:3000/about_me`. - -![image](https://user-images.githubusercontent.com/66632353/211770375-4cc14806-7e60-4135-9e40-7b73e3c4ed23.png) -![image](https://user-images.githubusercontent.com/66632353/211770741-56dfaea8-2095-474b-974a-2b151953a3de.png) +Once a table is created, we have to fill it with actual data. In +particular, we can create, read, update and destroy records in a table. +Each operation maps to a different SQL command and a different Rails +equivalent. -- Copy the test file from week_3 directory to hello_world/test/controllers: -```bash -cp page_controller_test.rb hello_world/test/controllers -``` +In this sub-task, we will work on some statistics from Football! + +Head over to [football](football/README.md) directory to learn more. + + +## Interactive Console -- Execute the test suite to ensure the page works as expected. +The Rails console is useful for testing out quick ideas with code and +debugging applications. ```bash -rails test +rails console ``` -- If the test fails, check the view files and debug the application. -- Once the test works locally, submit your changes. +This should open a console, similar to IRB in the first session. We can +access your model functions and execute any valid ruby code. -# Model -Once done head over to [football](./football) directory to learn more about models. \ No newline at end of file +- [The Rails Command Line](https://guides.rubyonrails.org/command_line.html#bin-rails-console) diff --git a/week_3/activity-tracker/.ruby-version b/week_3/activity-tracker/.ruby-version new file mode 100644 index 00000000..316881c9 --- /dev/null +++ b/week_3/activity-tracker/.ruby-version @@ -0,0 +1 @@ +ruby-3.0.5 diff --git a/week_3/activity-tracker/Gemfile b/week_3/activity-tracker/Gemfile new file mode 100644 index 00000000..0e74c513 --- /dev/null +++ b/week_3/activity-tracker/Gemfile @@ -0,0 +1,72 @@ +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby "3.0.5" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 7.0.4" + +# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] +gem "sprockets-rails" + +# Use sqlite3 as the database for Active Record +gem "sqlite3", "~> 1.4" + +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", "~> 5.0" + +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" + +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" + +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" + +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Redis adapter to run Action Cable in production +# gem "redis", "~> 4.0" + +# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] +# gem "kredis" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ] + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Use Sass to process CSS +# gem "sassc-rails" + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri mingw x64_mingw ] +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" + + # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler] + # gem "rack-mini-profiler" + + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" + gem "webdrivers" +end diff --git a/week_3/activity-tracker/Gemfile.lock b/week_3/activity-tracker/Gemfile.lock new file mode 100644 index 00000000..2429566c --- /dev/null +++ b/week_3/activity-tracker/Gemfile.lock @@ -0,0 +1,232 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.0.4) + actionpack (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activesupport (= 7.0.4) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.0) + actionpack (7.0.4) + actionview (= 7.0.4) + activesupport (= 7.0.4) + rack (~> 2.0, >= 2.2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (7.0.4) + actionpack (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.0.4) + activesupport (= 7.0.4) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.3.6) + activemodel (7.0.4) + activesupport (= 7.0.4) + activerecord (7.0.4) + activemodel (= 7.0.4) + activesupport (= 7.0.4) + activestorage (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activesupport (= 7.0.4) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (7.0.4) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + addressable (2.8.1) + public_suffix (>= 2.0.2, < 6.0) + bindex (0.8.1) + bootsnap (1.15.0) + msgpack (~> 1.2) + builder (3.2.4) + capybara (3.38.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.8) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + concurrent-ruby (1.1.10) + crass (1.0.6) + date (3.3.3) + debug (1.7.1) + irb (>= 1.5.0) + reline (>= 0.3.1) + erubi (1.12.0) + globalid (1.0.0) + activesupport (>= 5.0) + i18n (1.12.0) + concurrent-ruby (~> 1.0) + importmap-rails (1.1.5) + actionpack (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.6.0) + irb (1.6.2) + reline (>= 0.3.0) + jbuilder (2.11.5) + actionview (>= 5.0.0) + activesupport (>= 5.0.0) + loofah (2.19.1) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.8.0.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + matrix (0.4.2) + method_source (1.0.0) + mini_mime (1.1.2) + minitest (5.17.0) + msgpack (1.6.0) + net-imap (0.3.4) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.1) + timeout + net-smtp (0.3.3) + net-protocol + nio4r (2.5.8) + nokogiri (1.14.0-x86_64-linux) + racc (~> 1.4) + public_suffix (5.0.1) + puma (5.6.5) + nio4r (~> 2.0) + racc (1.6.2) + rack (2.2.5) + rack-test (2.0.2) + rack (>= 1.3) + rails (7.0.4) + actioncable (= 7.0.4) + actionmailbox (= 7.0.4) + actionmailer (= 7.0.4) + actionpack (= 7.0.4) + actiontext (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activemodel (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + bundler (>= 1.15.0) + railties (= 7.0.4) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.4.4) + loofah (~> 2.19, >= 2.19.1) + railties (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + method_source + rake (>= 12.2) + thor (~> 1.0) + zeitwerk (~> 2.5) + rake (13.0.6) + regexp_parser (2.6.1) + reline (0.3.2) + io-console (~> 0.5) + rexml (3.2.5) + rubyzip (2.3.2) + selenium-webdriver (4.7.1) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 3.0) + websocket (~> 1.0) + sprockets (4.2.0) + concurrent-ruby (~> 1.0) + rack (>= 2.2.4, < 4) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + sprockets (>= 3.0.0) + sqlite3 (1.5.4-x86_64-linux) + stimulus-rails (1.2.1) + railties (>= 6.0.0) + thor (1.2.1) + timeout (0.3.1) + turbo-rails (1.3.2) + actionpack (>= 6.0.0) + activejob (>= 6.0.0) + railties (>= 6.0.0) + tzinfo (2.0.5) + concurrent-ruby (~> 1.0) + web-console (4.2.0) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + webdrivers (5.2.0) + nokogiri (~> 1.6) + rubyzip (>= 1.3.0) + selenium-webdriver (~> 4.0) + websocket (1.2.9) + websocket-driver (0.7.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.6.6) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + bootsnap + capybara + debug + importmap-rails + jbuilder + puma (~> 5.0) + rails (~> 7.0.4) + selenium-webdriver + sprockets-rails + sqlite3 (~> 1.4) + stimulus-rails + turbo-rails + tzinfo-data + web-console + webdrivers + +RUBY VERSION + ruby 3.0.5p211 + +BUNDLED WITH + 2.2.33 diff --git a/week_3/activity-tracker/README.md b/week_3/activity-tracker/README.md new file mode 100644 index 00000000..169969be --- /dev/null +++ b/week_3/activity-tracker/README.md @@ -0,0 +1,151 @@ +# Creating Tables | Activity Tracker + +We will learn about creating tables in Rails while keeping ourselves fit! + +Tables are the database objects that contain all the data in a database. +In tables, data is locally organized in a row-and-column format similar +to a spreadsheet. Each row represents a unique record and each column +represents a field in the record. + +For example, a table that contains employee data might contain a row for +each employee and columns representing employee information such as +employee number, name, address, job title and phone number. + +Tables are created executing the SQL statement `CREATE TABLE` on the +database. For example: + +```sql +CREATE TABLE employees ( + employee_number INTEGER, + name VARCHAR(80), + address VARCHAR(255), + title VARCHAR(80), + phone_number VARCHAR(10) + salary DECIMAL +); +``` + +In Rails, each table represents a class in `app/models` and creating new +tables is simpler and more convenient, thanks to the generator and +migrations. + +Rails equivalent of the above statement would be: + +```bash +rails generate model Employee employee_number:integer name:string \ +address:string title:string phone_number:string{10} salary:decimal +``` + +For this exercise, we will create a table `activity` with the following +attributes and data-types: +- Title: `string` +- Type: `string` +- Start: `datetime` +- Duration: `decimal` +- Calories: `integer` + +## Steps + +1. ### Prepare Local Database + +- Change directory to activity-tracker + + ```bash + cd activity-tracker + ``` + +- Create the database + ``` + rails db:create + ``` + + You should see two new files are created if not present already - `development.sqlite3` and `test.sqlite3`. + + - Run the migrations + + ```bash + rails db:migrate + ``` + +2. ### Create the tables + Models can be created using Rails generator with the following syntax: + + ```bash + rails generate model NAME field[:type] field[:type]... + ``` + + So for our requirement, execute the following command: + ```bash + rails generate model Activity title:string type:string start:datetime duration:decimal calories:integer + ``` + + > Rails has great emphasis on naming conventions. The model name must be + > `CamelCase` and column names must be `snake_case`. Read about other + > [rails naming conventions](https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e). + + - [Understanding the SQL Decimal data type](https://www.sqlshack.com/understanding-sql-decimal-data-type/) + - [Precision and scale for decimals](https://millarian.com/rails/precision-and-scale-for-ruby-on-rails-migrations/) + + The command creates multiple files - most important of which are + `app/models/activity.rb` and `db/migrate/_create_activities.rb` + + > The number in the beginning of the migration file is a UTC timestamp. + > Rails uses this timestamp to determine which migration should be run + > and in what order. + + The file `db/migrations/_create_activities.rb` looks like: + + ```ruby + class CreateActivities < ActiveRecord::Migration[7.0] + def change + create_table :activities do |t| + t.string :title + t.string :type + t.datetime :start + t.decimal :duration + t.integer :calories + + t.timestamps + end + end + end + ``` + + The migration roughly translates to "create table activities with the five columns and their types described above" which is exactly what we wanted! + The migration also uses the code `t.timestamps` to add timestamps `created_at` and `updated_at` to the activities table automatically. + + - Run the migration. + + ```bash + rails db:migrate + ``` + + > Running the migration commits the changes to the database. Therefore, + > your changes are not reflected in the database unless migrated. + + - Execute the test suite and submit your changes when tests pass. + + ```bash + rails test + ``` + +
+ +## Rolling Back Migrations + +If the migration was incorrect (say wrong column names or datatype), +you can "undo" the migration by the following command: + +```bash +rails db:rollback +``` + +Then, fix the migration file `db/migrations/_create_students.rb` +and re-run the migration to commit your changes to the dabase. + +Read more about migrations at: [Running Migrations | Active Record Migrations](https://edgeguides.rubyonrails.org/active_record_migrations.html#rolling-back) + +
+ +## References +- [Rails Active Record Migration](https://guides.rubyonrails.org/active_record_migrations.html) diff --git a/week_3/activity-tracker/Rakefile b/week_3/activity-tracker/Rakefile new file mode 100644 index 00000000..9a5ea738 --- /dev/null +++ b/week_3/activity-tracker/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/week_3/activity-tracker/app/assets/config/manifest.js b/week_3/activity-tracker/app/assets/config/manifest.js new file mode 100644 index 00000000..ddd546a0 --- /dev/null +++ b/week_3/activity-tracker/app/assets/config/manifest.js @@ -0,0 +1,4 @@ +//= link_tree ../images +//= link_directory ../stylesheets .css +//= link_tree ../../javascript .js +//= link_tree ../../../vendor/javascript .js diff --git a/week_3/activity-tracker/app/assets/images/.keep b/week_3/activity-tracker/app/assets/images/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/app/assets/stylesheets/application.css b/week_3/activity-tracker/app/assets/stylesheets/application.css new file mode 100644 index 00000000..288b9ab7 --- /dev/null +++ b/week_3/activity-tracker/app/assets/stylesheets/application.css @@ -0,0 +1,15 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + *= require_tree . + *= require_self + */ diff --git a/week_3/activity-tracker/app/channels/application_cable/channel.rb b/week_3/activity-tracker/app/channels/application_cable/channel.rb new file mode 100644 index 00000000..d6726972 --- /dev/null +++ b/week_3/activity-tracker/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/week_3/activity-tracker/app/channels/application_cable/connection.rb b/week_3/activity-tracker/app/channels/application_cable/connection.rb new file mode 100644 index 00000000..0ff5442f --- /dev/null +++ b/week_3/activity-tracker/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/week_3/activity-tracker/app/controllers/application_controller.rb b/week_3/activity-tracker/app/controllers/application_controller.rb new file mode 100644 index 00000000..09705d12 --- /dev/null +++ b/week_3/activity-tracker/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::Base +end diff --git a/week_3/activity-tracker/app/controllers/concerns/.keep b/week_3/activity-tracker/app/controllers/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/app/helpers/application_helper.rb b/week_3/activity-tracker/app/helpers/application_helper.rb new file mode 100644 index 00000000..de6be794 --- /dev/null +++ b/week_3/activity-tracker/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/week_3/activity-tracker/app/javascript/application.js b/week_3/activity-tracker/app/javascript/application.js new file mode 100644 index 00000000..0d7b4940 --- /dev/null +++ b/week_3/activity-tracker/app/javascript/application.js @@ -0,0 +1,3 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" diff --git a/week_3/activity-tracker/app/javascript/controllers/application.js b/week_3/activity-tracker/app/javascript/controllers/application.js new file mode 100644 index 00000000..1213e85c --- /dev/null +++ b/week_3/activity-tracker/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/week_3/activity-tracker/app/javascript/controllers/hello_controller.js b/week_3/activity-tracker/app/javascript/controllers/hello_controller.js new file mode 100644 index 00000000..5975c078 --- /dev/null +++ b/week_3/activity-tracker/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/week_3/activity-tracker/app/javascript/controllers/index.js b/week_3/activity-tracker/app/javascript/controllers/index.js new file mode 100644 index 00000000..54ad4cad --- /dev/null +++ b/week_3/activity-tracker/app/javascript/controllers/index.js @@ -0,0 +1,11 @@ +// Import and register all your controllers from the importmap under controllers/* + +import { application } from "controllers/application" + +// Eager load all controllers defined in the import map under controllers/**/*_controller +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) + +// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!) +// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading" +// lazyLoadControllersFrom("controllers", application) diff --git a/week_3/activity-tracker/app/jobs/application_job.rb b/week_3/activity-tracker/app/jobs/application_job.rb new file mode 100644 index 00000000..d394c3d1 --- /dev/null +++ b/week_3/activity-tracker/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/week_3/activity-tracker/app/mailers/application_mailer.rb b/week_3/activity-tracker/app/mailers/application_mailer.rb new file mode 100644 index 00000000..3c34c814 --- /dev/null +++ b/week_3/activity-tracker/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/week_3/activity-tracker/app/models/application_record.rb b/week_3/activity-tracker/app/models/application_record.rb new file mode 100644 index 00000000..b63caeb8 --- /dev/null +++ b/week_3/activity-tracker/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/week_3/activity-tracker/app/models/concerns/.keep b/week_3/activity-tracker/app/models/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/app/views/layouts/application.html.erb b/week_3/activity-tracker/app/views/layouts/application.html.erb new file mode 100644 index 00000000..5f65d83d --- /dev/null +++ b/week_3/activity-tracker/app/views/layouts/application.html.erb @@ -0,0 +1,16 @@ + + + + ActivityTracker + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <%= yield %> + + diff --git a/week_3/activity-tracker/app/views/layouts/mailer.html.erb b/week_3/activity-tracker/app/views/layouts/mailer.html.erb new file mode 100644 index 00000000..cbd34d2e --- /dev/null +++ b/week_3/activity-tracker/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/week_3/activity-tracker/app/views/layouts/mailer.text.erb b/week_3/activity-tracker/app/views/layouts/mailer.text.erb new file mode 100644 index 00000000..37f0bddb --- /dev/null +++ b/week_3/activity-tracker/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/week_3/activity-tracker/bin/bundle b/week_3/activity-tracker/bin/bundle new file mode 100755 index 00000000..374a0a1f --- /dev/null +++ b/week_3/activity-tracker/bin/bundle @@ -0,0 +1,114 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../../Gemfile", __FILE__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + requirement = bundler_gem_version.approximate_recommendation + + return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0") + + requirement += ".a" if bundler_gem_version.prerelease? + + requirement + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/week_3/activity-tracker/bin/importmap b/week_3/activity-tracker/bin/importmap new file mode 100755 index 00000000..36502ab1 --- /dev/null +++ b/week_3/activity-tracker/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/week_3/activity-tracker/bin/rails b/week_3/activity-tracker/bin/rails new file mode 100755 index 00000000..efc03774 --- /dev/null +++ b/week_3/activity-tracker/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/week_3/activity-tracker/bin/rake b/week_3/activity-tracker/bin/rake new file mode 100755 index 00000000..4fbf10b9 --- /dev/null +++ b/week_3/activity-tracker/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/week_3/activity-tracker/bin/setup b/week_3/activity-tracker/bin/setup new file mode 100755 index 00000000..ec47b79b --- /dev/null +++ b/week_3/activity-tracker/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + puts "\n== Restarting application server ==" + system! "bin/rails restart" +end diff --git a/week_3/activity-tracker/config.ru b/week_3/activity-tracker/config.ru new file mode 100644 index 00000000..4a3c09a6 --- /dev/null +++ b/week_3/activity-tracker/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/week_3/activity-tracker/config/application.rb b/week_3/activity-tracker/config/application.rb new file mode 100644 index 00000000..eaab4107 --- /dev/null +++ b/week_3/activity-tracker/config/application.rb @@ -0,0 +1,22 @@ +require_relative "boot" + +require "rails/all" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ActivityTracker + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.0 + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + end +end diff --git a/week_3/activity-tracker/config/boot.rb b/week_3/activity-tracker/config/boot.rb new file mode 100644 index 00000000..988a5ddc --- /dev/null +++ b/week_3/activity-tracker/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/week_3/activity-tracker/config/cable.yml b/week_3/activity-tracker/config/cable.yml new file mode 100644 index 00000000..fc223da2 --- /dev/null +++ b/week_3/activity-tracker/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: activity_tracker_production diff --git a/week_3/activity-tracker/config/credentials.yml.enc b/week_3/activity-tracker/config/credentials.yml.enc new file mode 100644 index 00000000..4410c9ad --- /dev/null +++ b/week_3/activity-tracker/config/credentials.yml.enc @@ -0,0 +1 @@ +vy9Yyajw1b8PCBzOL90ahf4dlXAdev9jaGcu43MsIEltJ9tLudTQHZhztOYwXgig6D1/W6vai5IQKKPbfBCioSi0cdsXraMUQpVx6wPgHjU4CRMYm5gbMJ8MoGpTTRO3546ceKYioiXoAtBnnM6jyHlqdqPm/xIND5SfytLSBOJrUxg8v06TISxfhIbRlGneBeEV7I8HcrBC2ulCNToXou0oojijWGkCUYjFV/0452pmrHDX+HC4Psc252O0H7emGpqjh6puxAV6aYmiNU3cvqNjUQXxHmaH7N1jgAnR/5xB1bwZHKUB7ngTufyFzt+3ZQg5UCbuuJ+4f8lSGbrJUKNJjpVVwW5jNrRCrDm8ZMbvHCus2ApGtHu/vVjxw5bo3hWda83vQhVcBI74bNo5JnbzuKNhmQi8VEHm--ByL641PQMhBRCAI2--Mnwv25FxL4SSK6RIuW8L1Q== \ No newline at end of file diff --git a/week_3/activity-tracker/config/database.yml b/week_3/activity-tracker/config/database.yml new file mode 100644 index 00000000..fcba57f1 --- /dev/null +++ b/week_3/activity-tracker/config/database.yml @@ -0,0 +1,25 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: db/test.sqlite3 + +production: + <<: *default + database: db/production.sqlite3 diff --git a/week_3/activity-tracker/config/environment.rb b/week_3/activity-tracker/config/environment.rb new file mode 100644 index 00000000..cac53157 --- /dev/null +++ b/week_3/activity-tracker/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/week_3/activity-tracker/config/environments/development.rb b/week_3/activity-tracker/config/environments/development.rb new file mode 100644 index 00000000..f2a3adc8 --- /dev/null +++ b/week_3/activity-tracker/config/environments/development.rb @@ -0,0 +1,72 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing + config.server_timing = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + config.hosts << "mittal-parth-animated-cod-gpxgvr5gwp62v4v5-3000.preview.app.github.dev" + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true +end diff --git a/week_3/activity-tracker/config/environments/production.rb b/week_3/activity-tracker/config/environments/production.rb new file mode 100644 index 00000000..86a19e32 --- /dev/null +++ b/week_3/activity-tracker/config/environments/production.rb @@ -0,0 +1,93 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present? + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "activity_tracker_production" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require "syslog/logger" + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name") + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/week_3/activity-tracker/config/environments/test.rb b/week_3/activity-tracker/config/environments/test.rb new file mode 100644 index 00000000..6ea4d1e7 --- /dev/null +++ b/week_3/activity-tracker/config/environments/test.rb @@ -0,0 +1,60 @@ +require "active_support/core_ext/integer/time" + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Turn false under Spring and add config.action_view.cache_template_loading = true. + config.cache_classes = true + + # Eager loading loads your whole application. When running a single test locally, + # this probably isn't necessary. It's a good idea to do in a continuous integration + # system, or in some way before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true +end diff --git a/week_3/activity-tracker/config/importmap.rb b/week_3/activity-tracker/config/importmap.rb new file mode 100644 index 00000000..8dce42d4 --- /dev/null +++ b/week_3/activity-tracker/config/importmap.rb @@ -0,0 +1,7 @@ +# Pin npm packages by running ./bin/importmap + +pin "application", preload: true +pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true +pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true +pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/week_3/activity-tracker/config/initializers/assets.rb b/week_3/activity-tracker/config/initializers/assets.rb new file mode 100644 index 00000000..2eeef966 --- /dev/null +++ b/week_3/activity-tracker/config/initializers/assets.rb @@ -0,0 +1,12 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/week_3/activity-tracker/config/initializers/content_security_policy.rb b/week_3/activity-tracker/config/initializers/content_security_policy.rb new file mode 100644 index 00000000..54f47cf1 --- /dev/null +++ b/week_3/activity-tracker/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap and inline scripts +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/week_3/activity-tracker/config/initializers/filter_parameter_logging.rb b/week_3/activity-tracker/config/initializers/filter_parameter_logging.rb new file mode 100644 index 00000000..adc6568c --- /dev/null +++ b/week_3/activity-tracker/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be filtered from the log file. Use this to limit dissemination of +# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported +# notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/week_3/activity-tracker/config/initializers/inflections.rb b/week_3/activity-tracker/config/initializers/inflections.rb new file mode 100644 index 00000000..3860f659 --- /dev/null +++ b/week_3/activity-tracker/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/week_3/activity-tracker/config/initializers/permissions_policy.rb b/week_3/activity-tracker/config/initializers/permissions_policy.rb new file mode 100644 index 00000000..00f64d71 --- /dev/null +++ b/week_3/activity-tracker/config/initializers/permissions_policy.rb @@ -0,0 +1,11 @@ +# Define an application-wide HTTP permissions policy. For further +# information see https://developers.google.com/web/updates/2018/06/feature-policy +# +# Rails.application.config.permissions_policy do |f| +# f.camera :none +# f.gyroscope :none +# f.microphone :none +# f.usb :none +# f.fullscreen :self +# f.payment :self, "https://secure.example.com" +# end diff --git a/week_3/activity-tracker/config/locales/en.yml b/week_3/activity-tracker/config/locales/en.yml new file mode 100644 index 00000000..8ca56fc7 --- /dev/null +++ b/week_3/activity-tracker/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# "true": "foo" +# +# To learn more, please read the Rails Internationalization guide +# available at https://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/week_3/activity-tracker/config/master.key b/week_3/activity-tracker/config/master.key new file mode 100644 index 00000000..3e69d63e --- /dev/null +++ b/week_3/activity-tracker/config/master.key @@ -0,0 +1 @@ +7ffae4e43de01027f283f3630db4227c \ No newline at end of file diff --git a/week_3/activity-tracker/config/puma.rb b/week_3/activity-tracker/config/puma.rb new file mode 100644 index 00000000..daaf0369 --- /dev/null +++ b/week_3/activity-tracker/config/puma.rb @@ -0,0 +1,43 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +# +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart diff --git a/week_3/activity-tracker/config/routes.rb b/week_3/activity-tracker/config/routes.rb new file mode 100644 index 00000000..262ffd54 --- /dev/null +++ b/week_3/activity-tracker/config/routes.rb @@ -0,0 +1,6 @@ +Rails.application.routes.draw do + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Defines the root path route ("/") + # root "articles#index" +end diff --git a/week_3/activity-tracker/config/storage.yml b/week_3/activity-tracker/config/storage.yml new file mode 100644 index 00000000..4942ab66 --- /dev/null +++ b/week_3/activity-tracker/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/week_3/activity-tracker/db/seeds.rb b/week_3/activity-tracker/db/seeds.rb new file mode 100644 index 00000000..bc25fce3 --- /dev/null +++ b/week_3/activity-tracker/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }]) +# Character.create(name: "Luke", movie: movies.first) diff --git a/week_3/activity-tracker/lib/assets/.keep b/week_3/activity-tracker/lib/assets/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/lib/tasks/.keep b/week_3/activity-tracker/lib/tasks/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/public/404.html b/week_3/activity-tracker/public/404.html new file mode 100644 index 00000000..2be3af26 --- /dev/null +++ b/week_3/activity-tracker/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_3/activity-tracker/public/422.html b/week_3/activity-tracker/public/422.html new file mode 100644 index 00000000..c08eac0d --- /dev/null +++ b/week_3/activity-tracker/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_3/activity-tracker/public/500.html b/week_3/activity-tracker/public/500.html new file mode 100644 index 00000000..78a030af --- /dev/null +++ b/week_3/activity-tracker/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_3/activity-tracker/public/apple-touch-icon-precomposed.png b/week_3/activity-tracker/public/apple-touch-icon-precomposed.png new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/public/apple-touch-icon.png b/week_3/activity-tracker/public/apple-touch-icon.png new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/public/favicon.ico b/week_3/activity-tracker/public/favicon.ico new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/public/robots.txt b/week_3/activity-tracker/public/robots.txt new file mode 100644 index 00000000..c19f78ab --- /dev/null +++ b/week_3/activity-tracker/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/week_3/activity-tracker/storage/.keep b/week_3/activity-tracker/storage/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/application_system_test_case.rb b/week_3/activity-tracker/test/application_system_test_case.rb new file mode 100644 index 00000000..d19212ab --- /dev/null +++ b/week_3/activity-tracker/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [1400, 1400] +end diff --git a/week_3/activity-tracker/test/channels/application_cable/connection_test.rb b/week_3/activity-tracker/test/channels/application_cable/connection_test.rb new file mode 100644 index 00000000..800405f1 --- /dev/null +++ b/week_3/activity-tracker/test/channels/application_cable/connection_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase + # test "connects with cookies" do + # cookies.signed[:user_id] = 42 + # + # connect + # + # assert_equal connection.user_id, "42" + # end +end diff --git a/week_3/activity-tracker/test/controllers/.keep b/week_3/activity-tracker/test/controllers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/fixtures/files/.keep b/week_3/activity-tracker/test/fixtures/files/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/helpers/.keep b/week_3/activity-tracker/test/helpers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/integration/.keep b/week_3/activity-tracker/test/integration/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/mailers/.keep b/week_3/activity-tracker/test/mailers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/models/.keep b/week_3/activity-tracker/test/models/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/models/activity_model_test.rb b/week_3/activity-tracker/test/models/activity_model_test.rb new file mode 100644 index 00000000..9af6029e --- /dev/null +++ b/week_3/activity-tracker/test/models/activity_model_test.rb @@ -0,0 +1,23 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + test 'has a string column title' do + assert_equal :string, Activity.type_for_attribute('title').type + end + + test 'has a string column type' do + assert_equal :string, Activity.type_for_attribute('type').type + end + + test 'has a datetime column start' do + assert_equal :datetime, Activity.type_for_attribute('start').type + end + + test 'has a decimal column duration' do + assert_equal :decimal, Activity.type_for_attribute('duration').type + end + + test 'has an integer column calories' do + assert_equal :integer, Activity.type_for_attribute('calories').type + end +end \ No newline at end of file diff --git a/week_3/activity-tracker/test/models/activity_test.rb b/week_3/activity-tracker/test/models/activity_test.rb new file mode 100644 index 00000000..c07a8b91 --- /dev/null +++ b/week_3/activity-tracker/test/models/activity_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/week_3/activity-tracker/test/system/.keep b/week_3/activity-tracker/test/system/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/test/test_helper.rb b/week_3/activity-tracker/test/test_helper.rb new file mode 100644 index 00000000..d713e377 --- /dev/null +++ b/week_3/activity-tracker/test/test_helper.rb @@ -0,0 +1,13 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +class ActiveSupport::TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/week_3/activity-tracker/vendor/.keep b/week_3/activity-tracker/vendor/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/activity-tracker/vendor/javascript/.keep b/week_3/activity-tracker/vendor/javascript/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_3/getting_started_with_rails.md b/week_3/getting_started_with_rails.md new file mode 100644 index 00000000..453ed55f --- /dev/null +++ b/week_3/getting_started_with_rails.md @@ -0,0 +1,82 @@ + +## Steps +- [Set Up Local Workplace](../setup/) + +- Create a new [gemset](../setup/README.md#RVM) and install rails +```bash +cd week_3 +rvm gemset create week_3 +rvm use 3.0.5@week_3 +gem install rails --version 7.0.4 +``` + +- Create a new Rails project `hello_world` in the directory `week_1` +```bash +rails new hello_world --css=bootstrap --skip-git +cd hello_world +rvm use 3.0.5@week_3 +``` + +> The command `rails new` initialises a Rails project. We have passed +> the flag `--skip-git` to avoid initializing Git again as we are +> already within a Git repository. + +- Run the rails server using below command and go to http://localhost:3000/. +```bash +rails server +``` + +You should see the rails logo. + +### Add a controller + +- Generate a new controller `PageController` with actions `root` and + `about_me`: + +```bash +rails generate controller Page root about_me +``` + +> A _controller_ is responsible for making sense of request and producing +> the appropriate output. It acts as a middleman between the Data +> (Model) and Presentation (View). Controllers are stored in +> `app/controllers` directory. + + +> The generator creates the files and fills it with some default code. +> the above command creates a controller +> `PagesController`, creates new view files `root.html.erb` and +> `about_me.html.erb` and modifies the routes file + +- Edit the routes file (`config/routes.rb`) as follow to add new routes: + +```ruby +Rails.application.routes.draw do + get '/', to: 'page#root' + get 'about_me', to: 'page#about_me' +end +``` + +The routes file specifies the URLs that are recognized by the application. + +- Edit the view files `app/views/page/root.html.erb` and `app/views/page/about_me.html.erb`. + +- You should be able to see see your changes at `http://localhost:3000` and + `http://localhost:3000/about_me`. + +![image](https://user-images.githubusercontent.com/66632353/211770375-4cc14806-7e60-4135-9e40-7b73e3c4ed23.png) +![image](https://user-images.githubusercontent.com/66632353/211770741-56dfaea8-2095-474b-974a-2b151953a3de.png) + +- Copy the test file from week_3 directory to hello_world/test/controllers: +```bash +cp page_controller_test.rb hello_world/test/controllers +``` + +- Execute the test suite to ensure the page works as expected. + +```bash +rails test +``` +- If the test fails, check the view files and debug the application. + +- Once the test works locally, submit your changes. \ No newline at end of file From c6dea6820595eb3621bce718bde27e491f39c4c8 Mon Sep 17 00:00:00 2001 From: Hrushikesh <66632353+hrushikeshj@users.noreply.github.com> Date: Wed, 18 Jan 2023 21:16:48 +0530 Subject: [PATCH 06/13] Update README.md --- week_3/football/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/week_3/football/README.md b/week_3/football/README.md index b6e1a06c..9871d3b8 100644 --- a/week_3/football/README.md +++ b/week_3/football/README.md @@ -75,6 +75,9 @@ rails db:fixtures:load ``` This adds some sample data(/test/fixtures/football_players.yml) to the database. +## Assignment +> For this assignment you have to implement the function inside [app/models/football_player.rb](https://github.com/IRIS-NITK/IRIS-RoR-Bootcamp-2022/blob/main/week_3/football/app/models/football_player.rb) + ### Creating Records The INSERT INTO statement is used to insert new records in a table From 4db1b661b10dff687b325f3005f9d2c4b287ac0f Mon Sep 17 00:00:00 2001 From: Hrushikesh <66632353+hrushikeshj@users.noreply.github.com> Date: Wed, 18 Jan 2023 21:40:50 +0530 Subject: [PATCH 07/13] Update README.md --- week_3/football/README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/week_3/football/README.md b/week_3/football/README.md index 9871d3b8..c642794a 100644 --- a/week_3/football/README.md +++ b/week_3/football/README.md @@ -220,6 +220,12 @@ FootballPlayer.find_by(name: "Messi").destroy - [DELETE | ActiveRecord](https://guides.rubyonrails.org/active_record_basics.html#delete) +Once you start implementing functions in app/models/football_player.rb, you can test your code. + +```bash +rails test:models +``` + # Rails console The Rails console is useful for testing out quick ideas with code and debugging applications. From a02d6d9add6aa393e76b40e1d7fcf6ccaea0ffd7 Mon Sep 17 00:00:00 2001 From: Parth Mittal <76661350+mittal-parth@users.noreply.github.com> Date: Sun, 29 Jan 2023 21:18:27 +0530 Subject: [PATCH 08/13] Add Week 4 Resources (#113) Added week 4 resources - controllers and devise. Co-authored-by: Anirudh Prabhakaran --- .github/workflows/week4_assignement.yml | 35 +++ week_4/README.md | 17 ++ week_4/activity-tracker/.ruby-version | 1 + week_4/activity-tracker/.tool-versions | 2 + week_4/activity-tracker/Gemfile | 74 ++++++ week_4/activity-tracker/Gemfile.lock | 237 ++++++++++++++++++ week_4/activity-tracker/README.md | 151 +++++++++++ week_4/activity-tracker/Rakefile | 6 + .../app/assets/config/manifest.js | 4 + .../activity-tracker/app/assets/images/.keep | 0 .../app/assets/stylesheets/application.css | 15 ++ .../app/channels/application_cable/channel.rb | 4 + .../channels/application_cable/connection.rb | 4 + .../app/controllers/activities_controller.rb | 70 ++++++ .../app/controllers/application_controller.rb | 2 + .../app/controllers/concerns/.keep | 0 .../app/helpers/activities_helper.rb | 2 + .../app/helpers/application_helper.rb | 2 + .../app/javascript/application.js | 3 + .../app/javascript/controllers/application.js | 9 + .../controllers/hello_controller.js | 7 + .../app/javascript/controllers/index.js | 11 + .../app/jobs/application_job.rb | 7 + .../app/mailers/application_mailer.rb | 4 + .../activity-tracker/app/models/activity.rb | 2 + .../app/models/application_record.rb | 3 + .../app/models/concerns/.keep | 0 .../app/views/activities/_activity.html.erb | 27 ++ .../views/activities/_activity.json.jbuilder | 2 + .../app/views/activities/_form.html.erb | 42 ++++ .../app/views/activities/edit.html.erb | 10 + .../app/views/activities/index.html.erb | 14 ++ .../app/views/activities/index.json.jbuilder | 1 + .../app/views/activities/new.html.erb | 9 + .../app/views/activities/show.html.erb | 10 + .../app/views/activities/show.json.jbuilder | 1 + .../app/views/activities/stats.html.erb | 0 .../app/views/layouts/application.html.erb | 16 ++ .../app/views/layouts/mailer.html.erb | 13 + .../app/views/layouts/mailer.text.erb | 1 + week_4/activity-tracker/authentication.md | 31 +++ week_4/activity-tracker/bin/bundle | 114 +++++++++ week_4/activity-tracker/bin/importmap | 4 + week_4/activity-tracker/bin/rails | 4 + week_4/activity-tracker/bin/rake | 4 + week_4/activity-tracker/bin/setup | 33 +++ week_4/activity-tracker/config.ru | 6 + week_4/activity-tracker/config/application.rb | 22 ++ week_4/activity-tracker/config/boot.rb | 4 + week_4/activity-tracker/config/cable.yml | 10 + .../config/credentials.yml.enc | 1 + week_4/activity-tracker/config/database.yml | 25 ++ week_4/activity-tracker/config/environment.rb | 5 + .../config/environments/development.rb | 72 ++++++ .../config/environments/production.rb | 93 +++++++ .../config/environments/test.rb | 60 +++++ week_4/activity-tracker/config/importmap.rb | 7 + .../config/initializers/assets.rb | 12 + .../initializers/content_security_policy.rb | 25 ++ .../initializers/filter_parameter_logging.rb | 8 + .../config/initializers/inflections.rb | 16 ++ .../config/initializers/permissions_policy.rb | 11 + week_4/activity-tracker/config/locales/en.yml | 33 +++ week_4/activity-tracker/config/master.key | 1 + week_4/activity-tracker/config/puma.rb | 43 ++++ week_4/activity-tracker/config/routes.rb | 8 + week_4/activity-tracker/config/storage.yml | 34 +++ .../20230127184553_create_activities.rb | 13 + week_4/activity-tracker/db/schema.rb | 24 ++ week_4/activity-tracker/db/seeds.rb | 7 + week_4/activity-tracker/lib/assets/.keep | 0 week_4/activity-tracker/lib/tasks/.keep | 0 week_4/activity-tracker/public/404.html | 67 +++++ week_4/activity-tracker/public/422.html | 67 +++++ week_4/activity-tracker/public/500.html | 66 +++++ .../public/apple-touch-icon-precomposed.png | 0 .../public/apple-touch-icon.png | 0 week_4/activity-tracker/public/favicon.ico | 0 week_4/activity-tracker/public/robots.txt | 1 + week_4/activity-tracker/storage/.keep | 0 .../test/application_system_test_case.rb | 5 + .../application_cable/connection_test.rb | 11 + .../activity-tracker/test/controllers/.keep | 0 .../controllers/activities_controller_test.rb | 59 +++++ .../test/fixtures/activities.yml | 15 ++ .../test/fixtures/files/.keep | 0 week_4/activity-tracker/test/helpers/.keep | 0 .../activity-tracker/test/integration/.keep | 0 week_4/activity-tracker/test/mailers/.keep | 0 week_4/activity-tracker/test/models/.keep | 0 .../test/models/activity_model_test.rb | 23 ++ .../test/models/activity_test.rb | 7 + week_4/activity-tracker/test/system/.keep | 0 .../test/system/activities_test.rb | 49 ++++ week_4/activity-tracker/test/test_helper.rb | 13 + week_4/activity-tracker/vendor/.keep | 0 .../activity-tracker/vendor/javascript/.keep | 0 97 files changed, 1931 insertions(+) create mode 100644 .github/workflows/week4_assignement.yml create mode 100644 week_4/README.md create mode 100644 week_4/activity-tracker/.ruby-version create mode 100644 week_4/activity-tracker/.tool-versions create mode 100644 week_4/activity-tracker/Gemfile create mode 100644 week_4/activity-tracker/Gemfile.lock create mode 100644 week_4/activity-tracker/README.md create mode 100644 week_4/activity-tracker/Rakefile create mode 100644 week_4/activity-tracker/app/assets/config/manifest.js create mode 100644 week_4/activity-tracker/app/assets/images/.keep create mode 100644 week_4/activity-tracker/app/assets/stylesheets/application.css create mode 100644 week_4/activity-tracker/app/channels/application_cable/channel.rb create mode 100644 week_4/activity-tracker/app/channels/application_cable/connection.rb create mode 100644 week_4/activity-tracker/app/controllers/activities_controller.rb create mode 100644 week_4/activity-tracker/app/controllers/application_controller.rb create mode 100644 week_4/activity-tracker/app/controllers/concerns/.keep create mode 100644 week_4/activity-tracker/app/helpers/activities_helper.rb create mode 100644 week_4/activity-tracker/app/helpers/application_helper.rb create mode 100644 week_4/activity-tracker/app/javascript/application.js create mode 100644 week_4/activity-tracker/app/javascript/controllers/application.js create mode 100644 week_4/activity-tracker/app/javascript/controllers/hello_controller.js create mode 100644 week_4/activity-tracker/app/javascript/controllers/index.js create mode 100644 week_4/activity-tracker/app/jobs/application_job.rb create mode 100644 week_4/activity-tracker/app/mailers/application_mailer.rb create mode 100644 week_4/activity-tracker/app/models/activity.rb create mode 100644 week_4/activity-tracker/app/models/application_record.rb create mode 100644 week_4/activity-tracker/app/models/concerns/.keep create mode 100644 week_4/activity-tracker/app/views/activities/_activity.html.erb create mode 100644 week_4/activity-tracker/app/views/activities/_activity.json.jbuilder create mode 100644 week_4/activity-tracker/app/views/activities/_form.html.erb create mode 100644 week_4/activity-tracker/app/views/activities/edit.html.erb create mode 100644 week_4/activity-tracker/app/views/activities/index.html.erb create mode 100644 week_4/activity-tracker/app/views/activities/index.json.jbuilder create mode 100644 week_4/activity-tracker/app/views/activities/new.html.erb create mode 100644 week_4/activity-tracker/app/views/activities/show.html.erb create mode 100644 week_4/activity-tracker/app/views/activities/show.json.jbuilder create mode 100644 week_4/activity-tracker/app/views/activities/stats.html.erb create mode 100644 week_4/activity-tracker/app/views/layouts/application.html.erb create mode 100644 week_4/activity-tracker/app/views/layouts/mailer.html.erb create mode 100644 week_4/activity-tracker/app/views/layouts/mailer.text.erb create mode 100644 week_4/activity-tracker/authentication.md create mode 100755 week_4/activity-tracker/bin/bundle create mode 100755 week_4/activity-tracker/bin/importmap create mode 100755 week_4/activity-tracker/bin/rails create mode 100755 week_4/activity-tracker/bin/rake create mode 100755 week_4/activity-tracker/bin/setup create mode 100644 week_4/activity-tracker/config.ru create mode 100644 week_4/activity-tracker/config/application.rb create mode 100644 week_4/activity-tracker/config/boot.rb create mode 100644 week_4/activity-tracker/config/cable.yml create mode 100644 week_4/activity-tracker/config/credentials.yml.enc create mode 100644 week_4/activity-tracker/config/database.yml create mode 100644 week_4/activity-tracker/config/environment.rb create mode 100644 week_4/activity-tracker/config/environments/development.rb create mode 100644 week_4/activity-tracker/config/environments/production.rb create mode 100644 week_4/activity-tracker/config/environments/test.rb create mode 100644 week_4/activity-tracker/config/importmap.rb create mode 100644 week_4/activity-tracker/config/initializers/assets.rb create mode 100644 week_4/activity-tracker/config/initializers/content_security_policy.rb create mode 100644 week_4/activity-tracker/config/initializers/filter_parameter_logging.rb create mode 100644 week_4/activity-tracker/config/initializers/inflections.rb create mode 100644 week_4/activity-tracker/config/initializers/permissions_policy.rb create mode 100644 week_4/activity-tracker/config/locales/en.yml create mode 100644 week_4/activity-tracker/config/master.key create mode 100644 week_4/activity-tracker/config/puma.rb create mode 100644 week_4/activity-tracker/config/routes.rb create mode 100644 week_4/activity-tracker/config/storage.yml create mode 100644 week_4/activity-tracker/db/migrate/20230127184553_create_activities.rb create mode 100644 week_4/activity-tracker/db/schema.rb create mode 100644 week_4/activity-tracker/db/seeds.rb create mode 100644 week_4/activity-tracker/lib/assets/.keep create mode 100644 week_4/activity-tracker/lib/tasks/.keep create mode 100644 week_4/activity-tracker/public/404.html create mode 100644 week_4/activity-tracker/public/422.html create mode 100644 week_4/activity-tracker/public/500.html create mode 100644 week_4/activity-tracker/public/apple-touch-icon-precomposed.png create mode 100644 week_4/activity-tracker/public/apple-touch-icon.png create mode 100644 week_4/activity-tracker/public/favicon.ico create mode 100644 week_4/activity-tracker/public/robots.txt create mode 100644 week_4/activity-tracker/storage/.keep create mode 100644 week_4/activity-tracker/test/application_system_test_case.rb create mode 100644 week_4/activity-tracker/test/channels/application_cable/connection_test.rb create mode 100644 week_4/activity-tracker/test/controllers/.keep create mode 100644 week_4/activity-tracker/test/controllers/activities_controller_test.rb create mode 100644 week_4/activity-tracker/test/fixtures/activities.yml create mode 100644 week_4/activity-tracker/test/fixtures/files/.keep create mode 100644 week_4/activity-tracker/test/helpers/.keep create mode 100644 week_4/activity-tracker/test/integration/.keep create mode 100644 week_4/activity-tracker/test/mailers/.keep create mode 100644 week_4/activity-tracker/test/models/.keep create mode 100644 week_4/activity-tracker/test/models/activity_model_test.rb create mode 100644 week_4/activity-tracker/test/models/activity_test.rb create mode 100644 week_4/activity-tracker/test/system/.keep create mode 100644 week_4/activity-tracker/test/system/activities_test.rb create mode 100644 week_4/activity-tracker/test/test_helper.rb create mode 100644 week_4/activity-tracker/vendor/.keep create mode 100644 week_4/activity-tracker/vendor/javascript/.keep diff --git a/.github/workflows/week4_assignement.yml b/.github/workflows/week4_assignement.yml new file mode 100644 index 00000000..12291a77 --- /dev/null +++ b/.github/workflows/week4_assignement.yml @@ -0,0 +1,35 @@ +name: 'Week 3 Model' + +on: + pull_request: + types: [synchronize, opened, reopened, edited] + branches: + - 'week4_*' + + workflow_dispatch: + +jobs: + week3_model: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Install Ruby + uses: ruby/setup-ruby@v1 + with: + working-directory: week_4/activity-tracker + bundler-cache: true + + - name: Install NPM packages + uses: bahmutov/npm-install@v1 + with: + working-directory: week_4/activity-tracker + + - name: Test Controller Actions + working-directory: week_4/activity-tracker + run: | + bundle exec rails db:create + bundle exec rails db:migrate + bundle exec rails test diff --git a/week_4/README.md b/week_4/README.md new file mode 100644 index 00000000..c322665f --- /dev/null +++ b/week_4/README.md @@ -0,0 +1,17 @@ +# Week 4 + +Hello! Hope you are having a wonderful time at the bootcamp. For this week, we will look into controllers, routing and authentication. You can find the links to the documents below. + +- [Controllers](./activity-tracker/README.md) +- [Authentication](./activity-tracker/authentication.md) + +## Assignement 1 +After going through the resource on controllers, it is time to make your own! Create a contoller action called `stats` that is invoked from the URL `/activities/stats/`. This controller action should define at least two *instance variables*: + +- `total_duration`: The total duration of all activity logged. +- `total_calories`: The total amount of calories burnt. + +Please ensure that you are able to access the URL from a browser. Also make sure that the variables are named **exactly** that. + +## Assignment 2 +Now that you have a functioning app ready, you need to protect it. You can't have anyone in the world access your activity logs, right? The task is simple - setup authentication! diff --git a/week_4/activity-tracker/.ruby-version b/week_4/activity-tracker/.ruby-version new file mode 100644 index 00000000..316881c9 --- /dev/null +++ b/week_4/activity-tracker/.ruby-version @@ -0,0 +1 @@ +ruby-3.0.5 diff --git a/week_4/activity-tracker/.tool-versions b/week_4/activity-tracker/.tool-versions new file mode 100644 index 00000000..4f7cf395 --- /dev/null +++ b/week_4/activity-tracker/.tool-versions @@ -0,0 +1,2 @@ +nodejs lts +ruby 3.0.5 diff --git a/week_4/activity-tracker/Gemfile b/week_4/activity-tracker/Gemfile new file mode 100644 index 00000000..413b15ae --- /dev/null +++ b/week_4/activity-tracker/Gemfile @@ -0,0 +1,74 @@ +source "https://rubygems.org" +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby "3.0.5" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 7.0.4" + +# The original asset pipeline for Rails [https://github.com/rails/sprockets-rails] +gem "sprockets-rails" + +# Use sqlite3 as the database for Active Record +gem "sqlite3", "~> 1.4" + +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", "~> 5.0" + +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" + +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" + +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" + +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Redis adapter to run Action Cable in production +# gem "redis", "~> 4.0" + +# Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis] +# gem "kredis" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ] + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Use Sass to process CSS +# gem "sassc-rails" + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri mingw x64_mingw ] +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" + + # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler] + # gem "rack-mini-profiler" + + # Speed up commands on slow machines / big apps [https://github.com/rails/spring] + # gem "spring" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" + gem "webdrivers" +end + +gem "rails-controller-testing" diff --git a/week_4/activity-tracker/Gemfile.lock b/week_4/activity-tracker/Gemfile.lock new file mode 100644 index 00000000..e8909a06 --- /dev/null +++ b/week_4/activity-tracker/Gemfile.lock @@ -0,0 +1,237 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + actionmailbox (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + mail (>= 2.7.1) + net-imap + net-pop + net-smtp + actionmailer (7.0.4) + actionpack (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activesupport (= 7.0.4) + mail (~> 2.5, >= 2.5.4) + net-imap + net-pop + net-smtp + rails-dom-testing (~> 2.0) + actionpack (7.0.4) + actionview (= 7.0.4) + activesupport (= 7.0.4) + rack (~> 2.0, >= 2.2.0) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.0, >= 1.2.0) + actiontext (7.0.4) + actionpack (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (7.0.4) + activesupport (= 7.0.4) + builder (~> 3.1) + erubi (~> 1.4) + rails-dom-testing (~> 2.0) + rails-html-sanitizer (~> 1.1, >= 1.2.0) + activejob (7.0.4) + activesupport (= 7.0.4) + globalid (>= 0.3.6) + activemodel (7.0.4) + activesupport (= 7.0.4) + activerecord (7.0.4) + activemodel (= 7.0.4) + activesupport (= 7.0.4) + activestorage (7.0.4) + actionpack (= 7.0.4) + activejob (= 7.0.4) + activerecord (= 7.0.4) + activesupport (= 7.0.4) + marcel (~> 1.0) + mini_mime (>= 1.1.0) + activesupport (7.0.4) + concurrent-ruby (~> 1.0, >= 1.0.2) + i18n (>= 1.6, < 2) + minitest (>= 5.1) + tzinfo (~> 2.0) + addressable (2.8.1) + public_suffix (>= 2.0.2, < 6.0) + bindex (0.8.1) + bootsnap (1.15.0) + msgpack (~> 1.2) + builder (3.2.4) + capybara (3.38.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.8) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + concurrent-ruby (1.1.10) + crass (1.0.6) + date (3.3.3) + debug (1.7.1) + irb (>= 1.5.0) + reline (>= 0.3.1) + erubi (1.12.0) + globalid (1.0.0) + activesupport (>= 5.0) + i18n (1.12.0) + concurrent-ruby (~> 1.0) + importmap-rails (1.1.5) + actionpack (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.6.0) + irb (1.6.2) + reline (>= 0.3.0) + jbuilder (2.11.5) + actionview (>= 5.0.0) + activesupport (>= 5.0.0) + loofah (2.19.1) + crass (~> 1.0.2) + nokogiri (>= 1.5.9) + mail (2.8.0.1) + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.0.2) + matrix (0.4.2) + method_source (1.0.0) + mini_mime (1.1.2) + minitest (5.17.0) + msgpack (1.6.0) + net-imap (0.3.4) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.1) + timeout + net-smtp (0.3.3) + net-protocol + nio4r (2.5.8) + nokogiri (1.14.0-x86_64-linux) + racc (~> 1.4) + public_suffix (5.0.1) + puma (5.6.5) + nio4r (~> 2.0) + racc (1.6.2) + rack (2.2.5) + rack-test (2.0.2) + rack (>= 1.3) + rails (7.0.4) + actioncable (= 7.0.4) + actionmailbox (= 7.0.4) + actionmailer (= 7.0.4) + actionpack (= 7.0.4) + actiontext (= 7.0.4) + actionview (= 7.0.4) + activejob (= 7.0.4) + activemodel (= 7.0.4) + activerecord (= 7.0.4) + activestorage (= 7.0.4) + activesupport (= 7.0.4) + bundler (>= 1.15.0) + railties (= 7.0.4) + rails-controller-testing (1.0.5) + actionpack (>= 5.0.1.rc1) + actionview (>= 5.0.1.rc1) + activesupport (>= 5.0.1.rc1) + rails-dom-testing (2.0.3) + activesupport (>= 4.2.0) + nokogiri (>= 1.6) + rails-html-sanitizer (1.4.4) + loofah (~> 2.19, >= 2.19.1) + railties (7.0.4) + actionpack (= 7.0.4) + activesupport (= 7.0.4) + method_source + rake (>= 12.2) + thor (~> 1.0) + zeitwerk (~> 2.5) + rake (13.0.6) + regexp_parser (2.6.1) + reline (0.3.2) + io-console (~> 0.5) + rexml (3.2.5) + rubyzip (2.3.2) + selenium-webdriver (4.7.1) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 3.0) + websocket (~> 1.0) + sprockets (4.2.0) + concurrent-ruby (~> 1.0) + rack (>= 2.2.4, < 4) + sprockets-rails (3.4.2) + actionpack (>= 5.2) + activesupport (>= 5.2) + sprockets (>= 3.0.0) + sqlite3 (1.5.4-x86_64-linux) + stimulus-rails (1.2.1) + railties (>= 6.0.0) + thor (1.2.1) + timeout (0.3.1) + turbo-rails (1.3.2) + actionpack (>= 6.0.0) + activejob (>= 6.0.0) + railties (>= 6.0.0) + tzinfo (2.0.5) + concurrent-ruby (~> 1.0) + web-console (4.2.0) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + webdrivers (5.2.0) + nokogiri (~> 1.6) + rubyzip (>= 1.3.0) + selenium-webdriver (~> 4.0) + websocket (1.2.9) + websocket-driver (0.7.5) + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.6.6) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + bootsnap + capybara + debug + importmap-rails + jbuilder + puma (~> 5.0) + rails (~> 7.0.4) + rails-controller-testing + selenium-webdriver + sprockets-rails + sqlite3 (~> 1.4) + stimulus-rails + turbo-rails + tzinfo-data + web-console + webdrivers + +RUBY VERSION + ruby 3.0.5p211 + +BUNDLED WITH + 2.2.33 diff --git a/week_4/activity-tracker/README.md b/week_4/activity-tracker/README.md new file mode 100644 index 00000000..c3248fd1 --- /dev/null +++ b/week_4/activity-tracker/README.md @@ -0,0 +1,151 @@ +# Controllers | Activity Tracker + +Alright! We have our model (which we will use to represent our data) ready to go. Now what we need to do is somehow be able to use this data to display content on our web app. + +Before we go into what controllers are, lets briefly look into what happens when a request is made to a Rails application. + +## Request Response Cycle +_(This is an oversimplification of the processes that happen under the hood. To know more details about what happens, you can refer to any resource about request-response cycle online.)_ + +The first thing that you would do is open up your browser, and enter a URL. Then some magic happens, and you can see the output webpage. Right? + +What happens internally is, every URL is mapped to a particular controller action. It is the controller's function to take over control, and fetch any necessary data it needs from database (via models that you made during the last week. Nice!). +This data is then packaged in appropriate formats - for example, if you are making an API server, your response would probably be in the JSON format. + +For a regular Rails app, the data from the controller is passed on the the special HTML pages, called _views_. In the views, you define how your data should be presented to the user. + +## Steps + +So lets recap. For making the web application work, we need: +- URLs. Each one of these are mapped to particular controller actions. +- Controllers. They aggregate all information needed for display, and pass it to the views. +- Views. They are what you see as the response. + +Quite a lot of steps right? Well, you're lucky you're learning Rails. + +## Scaffolding +There is a lot of "magic" that Rails does to make the developer's life much easier. One of the greatest ways, and very powerful tool that you'll be using often, is **scaffolds**. + +A scaffold basically does what it says - creates a lot of boilerplate code, so that you don't have to manually type it out. What is this boilerplate you ask? + +The scaffold operation creates the model, controller, views, routes and associated test files for the object that you specify. The URLs and controller actions that are made are the ones commonly used for CRUD operations - creating, removing, updating and deleting records. + +If it seems a little overwhelming to you right now, fear not! All shall be revealed soon. + +## Requirement +As a small recap, this is the data that we need in our application. + +- Title: `string` +- ActivityType: `string` +- Start: `datetime` +- Duration: `decimal` +- Calories: `integer` + +In the previous week, you might have generated the model for this using `rails generate model`. This time, we'll create a scaffold for this. + +```shell +rails generate scaffold Activity title:string activity_type:string start:datetime duration:decimal calories:integer +``` + +Make sure you keep in mind the Rails naming conventions! They apply here also. + +When you run this command, a ton of files would have been generated on your system. Lets take an overview of the files generated. + +- `create db/migrate/20230127173852_create_activities.rb`: Creating the migration file, to be applied to the database. +- `create app/models/activity.rb0`: The model file for our model. +- `create test/models/activity_test.rb`: Test file, for writing tests. +- `route resources :activities`: Routes (URLs). Add the basic CRUD URLs automatically. +- `create app/controllers/activities_controller.rb`: Controller. This is where you write controller actions. +- `create app/views/activities/*`: A bunch of files in this directory. These correspond to the views that will be rendered. +- `create test/controllers/activities_controller_test.rb`: Test suite for the controller. +- `create app/helpers/activities_helper.rb`: Helper for our resource. + +Ensure that you have created the database using `rails db:create`. You can now apply migrations created by using `rails db:migrate`. + +Run the server using `rails server`. If you now go to `localhost:3000/activities` on your browser, you can see a basic app in function! + +## The Controller +Now, lets open the controller and see what is happening. We'll take an example of a simple function, and try to understand what is happening. + +```ruby + def index + @activities = Activity.all + end +``` + +This is the `index` function. As the name suggests, this is the controller action that is called when you go to the home page. It displays a list of all the available entries for you to view (i.e. it provides an "index" of all data.) + +`Activity` refers to our model. The all function allows us to pick up all the entries that are stored as part of the `Activity` model, that is, all rows in the activities table. We save that in a variable called `@activities`. + +If you notice, the variable starts with `@`. This is a special type of variable in Rails, known as **instance variables**. These are variables that are accessible in both the controller and the views. + +At the end, we do not tell Rails to render any particular template (in opposition to some other frameworks, for instance Django). This is because of how Rails works - convention over configuration. Rails will automatically look for a file with the name `index.html` or `index.html.erb` (you'll learn about the `.erb` format when you learn about views), and directly render that file. +Pretty convenient, right? + +## `rails generate controller` +Scaffolding is an extremely easy and powerful way to bring up your resources. However, this is not the only way you can create controllers. +They can also be generated normally by + +```shell +rails generate controller NAME [action action] [options] +``` + +Using this, you can create your own controllers as well. They do not have to be always bound to a particular model +and can exist independently as well. + +## Routing +Now, we have all the CRUD URLs by default for us, thanks to scaffold. Let's dig a bit deeper into how routes works. +Open up `config/routes.rb`. Your file will look something like this: + +```ruby +Rails.application.routes.draw do + resources :activities + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Defines the root path route ("/") + # root "articles#index" +end + +``` + +This is the file where all routes for the application are defined. Whenever the server receives a request, it searches among this list of routes and controller action mappings to find what to do with the request. +Note the second line: + +```ruby +resources :activities +``` + +This is what generates all the CRUD operations on that model. In general, if you have a model, you can add all the CRUD operations by using `resources :NAME` without having to individually define routes. + +However, sometimes we need other routes too, and not just these basic ones. An example is the following: + +```ruby + get 'about', to: "pages#about" +``` + +This tells Rails to dispatch a GET request to `/about` to the `about` action of the `Pages` controller. The generic format is `GET/POST/etc 'route', to: 'controller#action'` + +But what if you wanted an additional route on your resource? Lets say you wanted the following routes: +- `/activity/load`: to load some activity data from another file. +- `/activity/:id/share`: to share your activity with friends. + +You could write these routes similar to the previous way; where you explicitly define the entire route. However, for URLs that add to resources, there is a better way. + +```ruby +resources :activities do + member do + get 'share' # GET /activity/:id/share + end + collection do + get 'load' # GET /activities/load + end +end +``` + +`member` adds the route to every individual record of that item, making routes that contain the ID of the item. `collection` adds the route to the entire collection, and so there are no IDs to the URL. +Not providing `to:` will tell Rails to look for a action with the same name as the URL, in the controller for that model. + +## References +- [Rails Routing from the Outside In](https://guides.rubyonrails.org/routing.html) +- [Action Controllers](https://guides.rubyonrails.org/action_controller_overview.html) +- [Layouts and Rendering in Rails (Views)](https://guides.rubyonrails.org/layouts_and_rendering.html) \ No newline at end of file diff --git a/week_4/activity-tracker/Rakefile b/week_4/activity-tracker/Rakefile new file mode 100644 index 00000000..9a5ea738 --- /dev/null +++ b/week_4/activity-tracker/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/week_4/activity-tracker/app/assets/config/manifest.js b/week_4/activity-tracker/app/assets/config/manifest.js new file mode 100644 index 00000000..ddd546a0 --- /dev/null +++ b/week_4/activity-tracker/app/assets/config/manifest.js @@ -0,0 +1,4 @@ +//= link_tree ../images +//= link_directory ../stylesheets .css +//= link_tree ../../javascript .js +//= link_tree ../../../vendor/javascript .js diff --git a/week_4/activity-tracker/app/assets/images/.keep b/week_4/activity-tracker/app/assets/images/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/app/assets/stylesheets/application.css b/week_4/activity-tracker/app/assets/stylesheets/application.css new file mode 100644 index 00000000..288b9ab7 --- /dev/null +++ b/week_4/activity-tracker/app/assets/stylesheets/application.css @@ -0,0 +1,15 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS (and SCSS, if configured) file within this directory, lib/assets/stylesheets, or any plugin's + * vendor/assets/stylesheets directory can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any other CSS + * files in this directory. Styles in this file should be added after the last require_* statement. + * It is generally better to create a new file per style scope. + * + *= require_tree . + *= require_self + */ diff --git a/week_4/activity-tracker/app/channels/application_cable/channel.rb b/week_4/activity-tracker/app/channels/application_cable/channel.rb new file mode 100644 index 00000000..d6726972 --- /dev/null +++ b/week_4/activity-tracker/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/week_4/activity-tracker/app/channels/application_cable/connection.rb b/week_4/activity-tracker/app/channels/application_cable/connection.rb new file mode 100644 index 00000000..0ff5442f --- /dev/null +++ b/week_4/activity-tracker/app/channels/application_cable/connection.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + end +end diff --git a/week_4/activity-tracker/app/controllers/activities_controller.rb b/week_4/activity-tracker/app/controllers/activities_controller.rb new file mode 100644 index 00000000..a1dc90c1 --- /dev/null +++ b/week_4/activity-tracker/app/controllers/activities_controller.rb @@ -0,0 +1,70 @@ +class ActivitiesController < ApplicationController + before_action :set_activity, only: %i[ show edit update destroy ] + + # GET /activities or /activities.json + def index + @activities = Activity.all + end + + # GET /activities/1 or /activities/1.json + def show + end + + # GET /activities/new + def new + @activity = Activity.new + end + + # GET /activities/1/edit + def edit + end + + # POST /activities or /activities.json + def create + @activity = Activity.new(activity_params) + + respond_to do |format| + if @activity.save + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully created." } + format.json { render :show, status: :created, location: @activity } + else + format.html { render :new, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + + # PATCH/PUT /activities/1 or /activities/1.json + def update + respond_to do |format| + if @activity.update(activity_params) + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully updated." } + format.json { render :show, status: :ok, location: @activity } + else + format.html { render :edit, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + + # DELETE /activities/1 or /activities/1.json + def destroy + @activity.destroy + + respond_to do |format| + format.html { redirect_to activities_url, notice: "Activity was successfully destroyed." } + format.json { head :no_content } + end + end + + private + # Use callbacks to share common setup or constraints between actions. + def set_activity + @activity = Activity.find(params[:id]) + end + + # Only allow a list of trusted parameters through. + def activity_params + params.require(:activity).permit(:title, :activity_type, :start, :duration, :calories) + end +end diff --git a/week_4/activity-tracker/app/controllers/application_controller.rb b/week_4/activity-tracker/app/controllers/application_controller.rb new file mode 100644 index 00000000..09705d12 --- /dev/null +++ b/week_4/activity-tracker/app/controllers/application_controller.rb @@ -0,0 +1,2 @@ +class ApplicationController < ActionController::Base +end diff --git a/week_4/activity-tracker/app/controllers/concerns/.keep b/week_4/activity-tracker/app/controllers/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/app/helpers/activities_helper.rb b/week_4/activity-tracker/app/helpers/activities_helper.rb new file mode 100644 index 00000000..4e9784cc --- /dev/null +++ b/week_4/activity-tracker/app/helpers/activities_helper.rb @@ -0,0 +1,2 @@ +module ActivitiesHelper +end diff --git a/week_4/activity-tracker/app/helpers/application_helper.rb b/week_4/activity-tracker/app/helpers/application_helper.rb new file mode 100644 index 00000000..de6be794 --- /dev/null +++ b/week_4/activity-tracker/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/week_4/activity-tracker/app/javascript/application.js b/week_4/activity-tracker/app/javascript/application.js new file mode 100644 index 00000000..0d7b4940 --- /dev/null +++ b/week_4/activity-tracker/app/javascript/application.js @@ -0,0 +1,3 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" diff --git a/week_4/activity-tracker/app/javascript/controllers/application.js b/week_4/activity-tracker/app/javascript/controllers/application.js new file mode 100644 index 00000000..1213e85c --- /dev/null +++ b/week_4/activity-tracker/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/week_4/activity-tracker/app/javascript/controllers/hello_controller.js b/week_4/activity-tracker/app/javascript/controllers/hello_controller.js new file mode 100644 index 00000000..5975c078 --- /dev/null +++ b/week_4/activity-tracker/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/week_4/activity-tracker/app/javascript/controllers/index.js b/week_4/activity-tracker/app/javascript/controllers/index.js new file mode 100644 index 00000000..54ad4cad --- /dev/null +++ b/week_4/activity-tracker/app/javascript/controllers/index.js @@ -0,0 +1,11 @@ +// Import and register all your controllers from the importmap under controllers/* + +import { application } from "controllers/application" + +// Eager load all controllers defined in the import map under controllers/**/*_controller +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) + +// Lazy load controllers as they appear in the DOM (remember not to preload controllers in import map!) +// import { lazyLoadControllersFrom } from "@hotwired/stimulus-loading" +// lazyLoadControllersFrom("controllers", application) diff --git a/week_4/activity-tracker/app/jobs/application_job.rb b/week_4/activity-tracker/app/jobs/application_job.rb new file mode 100644 index 00000000..d394c3d1 --- /dev/null +++ b/week_4/activity-tracker/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/week_4/activity-tracker/app/mailers/application_mailer.rb b/week_4/activity-tracker/app/mailers/application_mailer.rb new file mode 100644 index 00000000..3c34c814 --- /dev/null +++ b/week_4/activity-tracker/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/week_4/activity-tracker/app/models/activity.rb b/week_4/activity-tracker/app/models/activity.rb new file mode 100644 index 00000000..a99f990d --- /dev/null +++ b/week_4/activity-tracker/app/models/activity.rb @@ -0,0 +1,2 @@ +class Activity < ApplicationRecord +end diff --git a/week_4/activity-tracker/app/models/application_record.rb b/week_4/activity-tracker/app/models/application_record.rb new file mode 100644 index 00000000..b63caeb8 --- /dev/null +++ b/week_4/activity-tracker/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/week_4/activity-tracker/app/models/concerns/.keep b/week_4/activity-tracker/app/models/concerns/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/app/views/activities/_activity.html.erb b/week_4/activity-tracker/app/views/activities/_activity.html.erb new file mode 100644 index 00000000..aab462e3 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/_activity.html.erb @@ -0,0 +1,27 @@ +
+

+ Title: + <%= activity.title %> +

+ +

+ Activity type: + <%= activity.activity_type %> +

+ +

+ Start: + <%= activity.start %> +

+ +

+ Duration: + <%= activity.duration %> +

+ +

+ Calories: + <%= activity.calories %> +

+ +
diff --git a/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder b/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder new file mode 100644 index 00000000..8efbd331 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder @@ -0,0 +1,2 @@ +json.extract! activity, :id, :title, :activity_type, :start, :duration, :calories, :created_at, :updated_at +json.url activity_url(activity, format: :json) diff --git a/week_4/activity-tracker/app/views/activities/_form.html.erb b/week_4/activity-tracker/app/views/activities/_form.html.erb new file mode 100644 index 00000000..6d4079c4 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/_form.html.erb @@ -0,0 +1,42 @@ +<%= form_with(model: activity) do |form| %> + <% if activity.errors.any? %> +
+

<%= pluralize(activity.errors.count, "error") %> prohibited this activity from being saved:

+ +
    + <% activity.errors.each do |error| %> +
  • <%= error.full_message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= form.label :title, style: "display: block" %> + <%= form.text_field :title %> +
+ +
+ <%= form.label :activity_type, style: "display: block" %> + <%= form.text_field :activity_type %> +
+ +
+ <%= form.label :start, style: "display: block" %> + <%= form.datetime_field :start %> +
+ +
+ <%= form.label :duration, style: "display: block" %> + <%= form.text_field :duration %> +
+ +
+ <%= form.label :calories, style: "display: block" %> + <%= form.number_field :calories %> +
+ +
+ <%= form.submit %> +
+<% end %> diff --git a/week_4/activity-tracker/app/views/activities/edit.html.erb b/week_4/activity-tracker/app/views/activities/edit.html.erb new file mode 100644 index 00000000..4774a05e --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/edit.html.erb @@ -0,0 +1,10 @@ +

Editing activity

+ +<%= render "form", activity: @activity %> + +
+ +
+ <%= link_to "Show this activity", @activity %> | + <%= link_to "Back to activities", activities_path %> +
diff --git a/week_4/activity-tracker/app/views/activities/index.html.erb b/week_4/activity-tracker/app/views/activities/index.html.erb new file mode 100644 index 00000000..776f9042 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/index.html.erb @@ -0,0 +1,14 @@ +

<%= notice %>

+ +

Activities

+ +
+ <% @activities.each do |activity| %> + <%= render activity %> +

+ <%= link_to "Show this activity", activity %> +

+ <% end %> +
+ +<%= link_to "New activity", new_activity_path %> diff --git a/week_4/activity-tracker/app/views/activities/index.json.jbuilder b/week_4/activity-tracker/app/views/activities/index.json.jbuilder new file mode 100644 index 00000000..865f89ee --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/index.json.jbuilder @@ -0,0 +1 @@ +json.array! @activities, partial: "activities/activity", as: :activity diff --git a/week_4/activity-tracker/app/views/activities/new.html.erb b/week_4/activity-tracker/app/views/activities/new.html.erb new file mode 100644 index 00000000..855a5899 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/new.html.erb @@ -0,0 +1,9 @@ +

New activity

+ +<%= render "form", activity: @activity %> + +
+ +
+ <%= link_to "Back to activities", activities_path %> +
diff --git a/week_4/activity-tracker/app/views/activities/show.html.erb b/week_4/activity-tracker/app/views/activities/show.html.erb new file mode 100644 index 00000000..73be1e19 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/show.html.erb @@ -0,0 +1,10 @@ +

<%= notice %>

+ +<%= render @activity %> + +
+ <%= link_to "Edit this activity", edit_activity_path(@activity) %> | + <%= link_to "Back to activities", activities_path %> + + <%= button_to "Destroy this activity", @activity, method: :delete %> +
diff --git a/week_4/activity-tracker/app/views/activities/show.json.jbuilder b/week_4/activity-tracker/app/views/activities/show.json.jbuilder new file mode 100644 index 00000000..a145d0a8 --- /dev/null +++ b/week_4/activity-tracker/app/views/activities/show.json.jbuilder @@ -0,0 +1 @@ +json.partial! "activities/activity", activity: @activity diff --git a/week_4/activity-tracker/app/views/activities/stats.html.erb b/week_4/activity-tracker/app/views/activities/stats.html.erb new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/app/views/layouts/application.html.erb b/week_4/activity-tracker/app/views/layouts/application.html.erb new file mode 100644 index 00000000..5f65d83d --- /dev/null +++ b/week_4/activity-tracker/app/views/layouts/application.html.erb @@ -0,0 +1,16 @@ + + + + ActivityTracker + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <%= yield %> + + diff --git a/week_4/activity-tracker/app/views/layouts/mailer.html.erb b/week_4/activity-tracker/app/views/layouts/mailer.html.erb new file mode 100644 index 00000000..cbd34d2e --- /dev/null +++ b/week_4/activity-tracker/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/week_4/activity-tracker/app/views/layouts/mailer.text.erb b/week_4/activity-tracker/app/views/layouts/mailer.text.erb new file mode 100644 index 00000000..37f0bddb --- /dev/null +++ b/week_4/activity-tracker/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/week_4/activity-tracker/authentication.md b/week_4/activity-tracker/authentication.md new file mode 100644 index 00000000..9621e41a --- /dev/null +++ b/week_4/activity-tracker/authentication.md @@ -0,0 +1,31 @@ +# Authentication | Activity Tracker + +Now that we have a good, functioning app ready, we need to secure it. Right now, anyone can access the data that we are entering. This is particularly concerning, since a lot of this might actually be sensitive information (especially in the case of a fitness tracker app), and needs to be secured properly. + +One way to do this is to allow only authorised users to be able to view the information stored. This is known as **authentication**. You provide basic information to prove that it is indeed you who are making the request, so that the application can trust you. + +In Rails, there is no in-built authentication system. However, there are great gems that are available for this very purpose. We will look at one of the most common ones, which is also in use at IRIS, called **Devise**. + +## Devise +`Devise` is an gem that provides authorisation capabilities to your Rails app, with very little difficulty. It is nearly completely customisable, and can be modified to fit all your individual needs. You can read a bit more about the project from the link in the references. + +We'll look at their README file, and quickly follow along to get it up and running. + +First, we need to get the gem. Add this to your `Gemfile` + +```ruby +gem 'devise' +``` + +Then we need to generate the files that Devise needs. This is done easily by the generater that the kind folks at Devise have made for us. + +```shell +$ rails generate devise:install +``` + +A few instructions would be printed onto your console. Make sure you follow them to properly set it up. + +Great job! Now you have Devise installed, you can set it up to protect your application. + +## References +- [Devise Repository](https://github.com/heartcombo/devise) \ No newline at end of file diff --git a/week_4/activity-tracker/bin/bundle b/week_4/activity-tracker/bin/bundle new file mode 100755 index 00000000..374a0a1f --- /dev/null +++ b/week_4/activity-tracker/bin/bundle @@ -0,0 +1,114 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../../Gemfile", __FILE__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + requirement = bundler_gem_version.approximate_recommendation + + return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0") + + requirement += ".a" if bundler_gem_version.prerelease? + + requirement + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/week_4/activity-tracker/bin/importmap b/week_4/activity-tracker/bin/importmap new file mode 100755 index 00000000..36502ab1 --- /dev/null +++ b/week_4/activity-tracker/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/week_4/activity-tracker/bin/rails b/week_4/activity-tracker/bin/rails new file mode 100755 index 00000000..efc03774 --- /dev/null +++ b/week_4/activity-tracker/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/week_4/activity-tracker/bin/rake b/week_4/activity-tracker/bin/rake new file mode 100755 index 00000000..4fbf10b9 --- /dev/null +++ b/week_4/activity-tracker/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/week_4/activity-tracker/bin/setup b/week_4/activity-tracker/bin/setup new file mode 100755 index 00000000..ec47b79b --- /dev/null +++ b/week_4/activity-tracker/bin/setup @@ -0,0 +1,33 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + puts "\n== Restarting application server ==" + system! "bin/rails restart" +end diff --git a/week_4/activity-tracker/config.ru b/week_4/activity-tracker/config.ru new file mode 100644 index 00000000..4a3c09a6 --- /dev/null +++ b/week_4/activity-tracker/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/week_4/activity-tracker/config/application.rb b/week_4/activity-tracker/config/application.rb new file mode 100644 index 00000000..eaab4107 --- /dev/null +++ b/week_4/activity-tracker/config/application.rb @@ -0,0 +1,22 @@ +require_relative "boot" + +require "rails/all" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module ActivityTracker + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 7.0 + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + end +end diff --git a/week_4/activity-tracker/config/boot.rb b/week_4/activity-tracker/config/boot.rb new file mode 100644 index 00000000..988a5ddc --- /dev/null +++ b/week_4/activity-tracker/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/week_4/activity-tracker/config/cable.yml b/week_4/activity-tracker/config/cable.yml new file mode 100644 index 00000000..fc223da2 --- /dev/null +++ b/week_4/activity-tracker/config/cable.yml @@ -0,0 +1,10 @@ +development: + adapter: async + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + channel_prefix: activity_tracker_production diff --git a/week_4/activity-tracker/config/credentials.yml.enc b/week_4/activity-tracker/config/credentials.yml.enc new file mode 100644 index 00000000..4410c9ad --- /dev/null +++ b/week_4/activity-tracker/config/credentials.yml.enc @@ -0,0 +1 @@ +vy9Yyajw1b8PCBzOL90ahf4dlXAdev9jaGcu43MsIEltJ9tLudTQHZhztOYwXgig6D1/W6vai5IQKKPbfBCioSi0cdsXraMUQpVx6wPgHjU4CRMYm5gbMJ8MoGpTTRO3546ceKYioiXoAtBnnM6jyHlqdqPm/xIND5SfytLSBOJrUxg8v06TISxfhIbRlGneBeEV7I8HcrBC2ulCNToXou0oojijWGkCUYjFV/0452pmrHDX+HC4Psc252O0H7emGpqjh6puxAV6aYmiNU3cvqNjUQXxHmaH7N1jgAnR/5xB1bwZHKUB7ngTufyFzt+3ZQg5UCbuuJ+4f8lSGbrJUKNJjpVVwW5jNrRCrDm8ZMbvHCus2ApGtHu/vVjxw5bo3hWda83vQhVcBI74bNo5JnbzuKNhmQi8VEHm--ByL641PQMhBRCAI2--Mnwv25FxL4SSK6RIuW8L1Q== \ No newline at end of file diff --git a/week_4/activity-tracker/config/database.yml b/week_4/activity-tracker/config/database.yml new file mode 100644 index 00000000..fcba57f1 --- /dev/null +++ b/week_4/activity-tracker/config/database.yml @@ -0,0 +1,25 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: db/test.sqlite3 + +production: + <<: *default + database: db/production.sqlite3 diff --git a/week_4/activity-tracker/config/environment.rb b/week_4/activity-tracker/config/environment.rb new file mode 100644 index 00000000..cac53157 --- /dev/null +++ b/week_4/activity-tracker/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/week_4/activity-tracker/config/environments/development.rb b/week_4/activity-tracker/config/environments/development.rb new file mode 100644 index 00000000..f2a3adc8 --- /dev/null +++ b/week_4/activity-tracker/config/environments/development.rb @@ -0,0 +1,72 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing + config.server_timing = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + config.hosts << "mittal-parth-animated-cod-gpxgvr5gwp62v4v5-3000.preview.app.github.dev" + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true +end diff --git a/week_4/activity-tracker/config/environments/production.rb b/week_4/activity-tracker/config/environments/production.rb new file mode 100644 index 00000000..86a19e32 --- /dev/null +++ b/week_4/activity-tracker/config/environments/production.rb @@ -0,0 +1,93 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV["RAILS_SERVE_STATIC_FILES"].present? + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache + # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = "wss://example.com/cable" + # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :resque + # config.active_job.queue_name_prefix = "activity_tracker_production" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require "syslog/logger" + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new "app-name") + + if ENV["RAILS_LOG_TO_STDOUT"].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/week_4/activity-tracker/config/environments/test.rb b/week_4/activity-tracker/config/environments/test.rb new file mode 100644 index 00000000..6ea4d1e7 --- /dev/null +++ b/week_4/activity-tracker/config/environments/test.rb @@ -0,0 +1,60 @@ +require "active_support/core_ext/integer/time" + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Turn false under Spring and add config.action_view.cache_template_loading = true. + config.cache_classes = true + + # Eager loading loads your whole application. When running a single test locally, + # this probably isn't necessary. It's a good idea to do in a continuous integration + # system, or in some way before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + "Cache-Control" => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true +end diff --git a/week_4/activity-tracker/config/importmap.rb b/week_4/activity-tracker/config/importmap.rb new file mode 100644 index 00000000..8dce42d4 --- /dev/null +++ b/week_4/activity-tracker/config/importmap.rb @@ -0,0 +1,7 @@ +# Pin npm packages by running ./bin/importmap + +pin "application", preload: true +pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true +pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true +pin_all_from "app/javascript/controllers", under: "controllers" diff --git a/week_4/activity-tracker/config/initializers/assets.rb b/week_4/activity-tracker/config/initializers/assets.rb new file mode 100644 index 00000000..2eeef966 --- /dev/null +++ b/week_4/activity-tracker/config/initializers/assets.rb @@ -0,0 +1,12 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/week_4/activity-tracker/config/initializers/content_security_policy.rb b/week_4/activity-tracker/config/initializers/content_security_policy.rb new file mode 100644 index 00000000..54f47cf1 --- /dev/null +++ b/week_4/activity-tracker/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap and inline scripts +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/week_4/activity-tracker/config/initializers/filter_parameter_logging.rb b/week_4/activity-tracker/config/initializers/filter_parameter_logging.rb new file mode 100644 index 00000000..adc6568c --- /dev/null +++ b/week_4/activity-tracker/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be filtered from the log file. Use this to limit dissemination of +# sensitive information. See the ActiveSupport::ParameterFilter documentation for supported +# notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] diff --git a/week_4/activity-tracker/config/initializers/inflections.rb b/week_4/activity-tracker/config/initializers/inflections.rb new file mode 100644 index 00000000..3860f659 --- /dev/null +++ b/week_4/activity-tracker/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/week_4/activity-tracker/config/initializers/permissions_policy.rb b/week_4/activity-tracker/config/initializers/permissions_policy.rb new file mode 100644 index 00000000..00f64d71 --- /dev/null +++ b/week_4/activity-tracker/config/initializers/permissions_policy.rb @@ -0,0 +1,11 @@ +# Define an application-wide HTTP permissions policy. For further +# information see https://developers.google.com/web/updates/2018/06/feature-policy +# +# Rails.application.config.permissions_policy do |f| +# f.camera :none +# f.gyroscope :none +# f.microphone :none +# f.usb :none +# f.fullscreen :self +# f.payment :self, "https://secure.example.com" +# end diff --git a/week_4/activity-tracker/config/locales/en.yml b/week_4/activity-tracker/config/locales/en.yml new file mode 100644 index 00000000..8ca56fc7 --- /dev/null +++ b/week_4/activity-tracker/config/locales/en.yml @@ -0,0 +1,33 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# The following keys must be escaped otherwise they will not be retrieved by +# the default I18n backend: +# +# true, false, on, off, yes, no +# +# Instead, surround them with single quotes. +# +# en: +# "true": "foo" +# +# To learn more, please read the Rails Internationalization guide +# available at https://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/week_4/activity-tracker/config/master.key b/week_4/activity-tracker/config/master.key new file mode 100644 index 00000000..3e69d63e --- /dev/null +++ b/week_4/activity-tracker/config/master.key @@ -0,0 +1 @@ +7ffae4e43de01027f283f3630db4227c \ No newline at end of file diff --git a/week_4/activity-tracker/config/puma.rb b/week_4/activity-tracker/config/puma.rb new file mode 100644 index 00000000..daaf0369 --- /dev/null +++ b/week_4/activity-tracker/config/puma.rb @@ -0,0 +1,43 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `worker_timeout` threshold that Puma will use to wait before +# terminating a worker in development environments. +# +worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart diff --git a/week_4/activity-tracker/config/routes.rb b/week_4/activity-tracker/config/routes.rb new file mode 100644 index 00000000..9ee203b2 --- /dev/null +++ b/week_4/activity-tracker/config/routes.rb @@ -0,0 +1,8 @@ +Rails.application.routes.draw do + resources :activities + + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Defines the root path route ("/") + # root "articles#index" +end diff --git a/week_4/activity-tracker/config/storage.yml b/week_4/activity-tracker/config/storage.yml new file mode 100644 index 00000000..4942ab66 --- /dev/null +++ b/week_4/activity-tracker/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/week_4/activity-tracker/db/migrate/20230127184553_create_activities.rb b/week_4/activity-tracker/db/migrate/20230127184553_create_activities.rb new file mode 100644 index 00000000..d0fe3b06 --- /dev/null +++ b/week_4/activity-tracker/db/migrate/20230127184553_create_activities.rb @@ -0,0 +1,13 @@ +class CreateActivities < ActiveRecord::Migration[7.0] + def change + create_table :activities do |t| + t.string :title + t.string :activity_type + t.datetime :start + t.decimal :duration + t.integer :calories + + t.timestamps + end + end +end diff --git a/week_4/activity-tracker/db/schema.rb b/week_4/activity-tracker/db/schema.rb new file mode 100644 index 00000000..8543cda3 --- /dev/null +++ b/week_4/activity-tracker/db/schema.rb @@ -0,0 +1,24 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[7.0].define(version: 2023_01_27_184553) do + create_table "activities", force: :cascade do |t| + t.string "title" + t.string "activity_type" + t.datetime "start" + t.decimal "duration" + t.integer "calories" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + +end diff --git a/week_4/activity-tracker/db/seeds.rb b/week_4/activity-tracker/db/seeds.rb new file mode 100644 index 00000000..bc25fce3 --- /dev/null +++ b/week_4/activity-tracker/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Examples: +# +# movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }]) +# Character.create(name: "Luke", movie: movies.first) diff --git a/week_4/activity-tracker/lib/assets/.keep b/week_4/activity-tracker/lib/assets/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/lib/tasks/.keep b/week_4/activity-tracker/lib/tasks/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/public/404.html b/week_4/activity-tracker/public/404.html new file mode 100644 index 00000000..2be3af26 --- /dev/null +++ b/week_4/activity-tracker/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_4/activity-tracker/public/422.html b/week_4/activity-tracker/public/422.html new file mode 100644 index 00000000..c08eac0d --- /dev/null +++ b/week_4/activity-tracker/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_4/activity-tracker/public/500.html b/week_4/activity-tracker/public/500.html new file mode 100644 index 00000000..78a030af --- /dev/null +++ b/week_4/activity-tracker/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/week_4/activity-tracker/public/apple-touch-icon-precomposed.png b/week_4/activity-tracker/public/apple-touch-icon-precomposed.png new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/public/apple-touch-icon.png b/week_4/activity-tracker/public/apple-touch-icon.png new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/public/favicon.ico b/week_4/activity-tracker/public/favicon.ico new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/public/robots.txt b/week_4/activity-tracker/public/robots.txt new file mode 100644 index 00000000..c19f78ab --- /dev/null +++ b/week_4/activity-tracker/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/week_4/activity-tracker/storage/.keep b/week_4/activity-tracker/storage/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/test/application_system_test_case.rb b/week_4/activity-tracker/test/application_system_test_case.rb new file mode 100644 index 00000000..d19212ab --- /dev/null +++ b/week_4/activity-tracker/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :chrome, screen_size: [1400, 1400] +end diff --git a/week_4/activity-tracker/test/channels/application_cable/connection_test.rb b/week_4/activity-tracker/test/channels/application_cable/connection_test.rb new file mode 100644 index 00000000..800405f1 --- /dev/null +++ b/week_4/activity-tracker/test/channels/application_cable/connection_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase + # test "connects with cookies" do + # cookies.signed[:user_id] = 42 + # + # connect + # + # assert_equal connection.user_id, "42" + # end +end diff --git a/week_4/activity-tracker/test/controllers/.keep b/week_4/activity-tracker/test/controllers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/test/controllers/activities_controller_test.rb b/week_4/activity-tracker/test/controllers/activities_controller_test.rb new file mode 100644 index 00000000..f1d89c50 --- /dev/null +++ b/week_4/activity-tracker/test/controllers/activities_controller_test.rb @@ -0,0 +1,59 @@ +require "test_helper" + +class ActivitiesControllerTest < ActionDispatch::IntegrationTest + setup do + @activity = activities(:one) + end + + test "should get index" do + get activities_url + assert_response :success + end + + test "should get new" do + get new_activity_url + assert_response :success + end + + test "should create activity" do + assert_difference("Activity.count") do + post activities_url, params: { activity: { activity_type: @activity.activity_type, calories: @activity.calories, duration: @activity.duration, start: @activity.start, title: @activity.title } } + end + + assert_redirected_to activity_url(Activity.last) + end + + test "should show activity" do + get activity_url(@activity) + assert_response :success + end + + test "should get edit" do + get edit_activity_url(@activity) + assert_response :success + end + + test "should update activity" do + patch activity_url(@activity), params: { activity: { activity_type: @activity.activity_type, calories: @activity.calories, duration: @activity.duration, start: @activity.start, title: @activity.title } } + assert_redirected_to activity_url(@activity) + end + + test "should destroy activity" do + assert_difference("Activity.count", -1) do + delete activity_url(@activity) + end + + assert_redirected_to activities_url + end + + test "should get stats" do + get stats_activities_url + assert_response :success + expected_calories = Activity.sum(&:calories) + expected_duration = Activity.sum(&:duration) + cal = assigns(:total_calories) + dur = assigns(:total_duration) + assert_equal(expected_calories, cal) + assert_equal(expected_duration, dur) + end +end diff --git a/week_4/activity-tracker/test/fixtures/activities.yml b/week_4/activity-tracker/test/fixtures/activities.yml new file mode 100644 index 00000000..aff553eb --- /dev/null +++ b/week_4/activity-tracker/test/fixtures/activities.yml @@ -0,0 +1,15 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + title: MyString + activity_type: MyString + start: 2023-01-28 00:15:53 + duration: 9.99 + calories: 1 + +two: + title: MyString + activity_type: MyString + start: 2023-01-28 00:15:53 + duration: 9.99 + calories: 1 diff --git a/week_4/activity-tracker/test/fixtures/files/.keep b/week_4/activity-tracker/test/fixtures/files/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/test/helpers/.keep b/week_4/activity-tracker/test/helpers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/test/integration/.keep b/week_4/activity-tracker/test/integration/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/test/mailers/.keep b/week_4/activity-tracker/test/mailers/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/test/models/.keep b/week_4/activity-tracker/test/models/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/test/models/activity_model_test.rb b/week_4/activity-tracker/test/models/activity_model_test.rb new file mode 100644 index 00000000..3097c757 --- /dev/null +++ b/week_4/activity-tracker/test/models/activity_model_test.rb @@ -0,0 +1,23 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + test 'has a string column title' do + assert_equal :string, Activity.type_for_attribute('title').type + end + + test 'has a string column type' do + assert_equal :string, Activity.type_for_attribute('activity_type').type + end + + test 'has a datetime column start' do + assert_equal :datetime, Activity.type_for_attribute('start').type + end + + test 'has a decimal column duration' do + assert_equal :decimal, Activity.type_for_attribute('duration').type + end + + test 'has an integer column calories' do + assert_equal :integer, Activity.type_for_attribute('calories').type + end +end \ No newline at end of file diff --git a/week_4/activity-tracker/test/models/activity_test.rb b/week_4/activity-tracker/test/models/activity_test.rb new file mode 100644 index 00000000..c07a8b91 --- /dev/null +++ b/week_4/activity-tracker/test/models/activity_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class ActivityTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end diff --git a/week_4/activity-tracker/test/system/.keep b/week_4/activity-tracker/test/system/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/test/system/activities_test.rb b/week_4/activity-tracker/test/system/activities_test.rb new file mode 100644 index 00000000..15feb5a2 --- /dev/null +++ b/week_4/activity-tracker/test/system/activities_test.rb @@ -0,0 +1,49 @@ +require "application_system_test_case" + +class ActivitiesTest < ApplicationSystemTestCase + setup do + @activity = activities(:one) + end + + test "visiting the index" do + visit activities_url + assert_selector "h1", text: "Activities" + end + + test "should create activity" do + visit activities_url + click_on "New activity" + + fill_in "Activity type", with: @activity.activity_type + fill_in "Calories", with: @activity.calories + fill_in "Duration", with: @activity.duration + fill_in "Start", with: @activity.start + fill_in "Title", with: @activity.title + click_on "Create Activity" + + assert_text "Activity was successfully created" + click_on "Back" + end + + test "should update Activity" do + visit activity_url(@activity) + click_on "Edit this activity", match: :first + + fill_in "Activity type", with: @activity.activity_type + fill_in "Calories", with: @activity.calories + fill_in "Duration", with: @activity.duration + fill_in "Start", with: @activity.start + fill_in "Title", with: @activity.title + click_on "Update Activity" + + assert_text "Activity was successfully updated" + click_on "Back" + end + + test "should destroy Activity" do + visit activity_url(@activity) + click_on "Destroy this activity", match: :first + + assert_text "Activity was successfully destroyed" + end +end diff --git a/week_4/activity-tracker/test/test_helper.rb b/week_4/activity-tracker/test/test_helper.rb new file mode 100644 index 00000000..d713e377 --- /dev/null +++ b/week_4/activity-tracker/test/test_helper.rb @@ -0,0 +1,13 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +class ActiveSupport::TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... +end diff --git a/week_4/activity-tracker/vendor/.keep b/week_4/activity-tracker/vendor/.keep new file mode 100644 index 00000000..e69de29b diff --git a/week_4/activity-tracker/vendor/javascript/.keep b/week_4/activity-tracker/vendor/javascript/.keep new file mode 100644 index 00000000..e69de29b From ef8052b74e95947b87147e9b409466a00c886777 Mon Sep 17 00:00:00 2001 From: Parth Mittal <76661350+mittal-parth@users.noreply.github.com> Date: Mon, 30 Jan 2023 03:54:23 +0000 Subject: [PATCH 09/13] remove already scaffolded code --- .../app/controllers/activities_controller.rb | 70 ------------------- .../app/helpers/activities_helper.rb | 2 - .../activity-tracker/app/models/activity.rb | 2 - .../app/views/activities/_activity.html.erb | 27 ------- .../views/activities/_activity.json.jbuilder | 2 - .../app/views/activities/_form.html.erb | 42 ----------- .../app/views/activities/edit.html.erb | 10 --- .../app/views/activities/index.html.erb | 14 ---- .../app/views/activities/index.json.jbuilder | 1 - .../app/views/activities/new.html.erb | 9 --- .../app/views/activities/show.html.erb | 10 --- .../app/views/activities/show.json.jbuilder | 1 - .../app/views/activities/stats.html.erb | 0 week_4/activity-tracker/config/routes.rb | 1 - .../20230127184553_create_activities.rb | 13 ---- week_4/activity-tracker/db/schema.rb | 12 +--- .../test/fixtures/activities.yml | 15 ---- .../test/models/activity_test.rb | 7 -- .../test/system/activities_test.rb | 49 ------------- 19 files changed, 1 insertion(+), 286 deletions(-) delete mode 100644 week_4/activity-tracker/app/controllers/activities_controller.rb delete mode 100644 week_4/activity-tracker/app/helpers/activities_helper.rb delete mode 100644 week_4/activity-tracker/app/models/activity.rb delete mode 100644 week_4/activity-tracker/app/views/activities/_activity.html.erb delete mode 100644 week_4/activity-tracker/app/views/activities/_activity.json.jbuilder delete mode 100644 week_4/activity-tracker/app/views/activities/_form.html.erb delete mode 100644 week_4/activity-tracker/app/views/activities/edit.html.erb delete mode 100644 week_4/activity-tracker/app/views/activities/index.html.erb delete mode 100644 week_4/activity-tracker/app/views/activities/index.json.jbuilder delete mode 100644 week_4/activity-tracker/app/views/activities/new.html.erb delete mode 100644 week_4/activity-tracker/app/views/activities/show.html.erb delete mode 100644 week_4/activity-tracker/app/views/activities/show.json.jbuilder delete mode 100644 week_4/activity-tracker/app/views/activities/stats.html.erb delete mode 100644 week_4/activity-tracker/db/migrate/20230127184553_create_activities.rb delete mode 100644 week_4/activity-tracker/test/fixtures/activities.yml delete mode 100644 week_4/activity-tracker/test/models/activity_test.rb delete mode 100644 week_4/activity-tracker/test/system/activities_test.rb diff --git a/week_4/activity-tracker/app/controllers/activities_controller.rb b/week_4/activity-tracker/app/controllers/activities_controller.rb deleted file mode 100644 index a1dc90c1..00000000 --- a/week_4/activity-tracker/app/controllers/activities_controller.rb +++ /dev/null @@ -1,70 +0,0 @@ -class ActivitiesController < ApplicationController - before_action :set_activity, only: %i[ show edit update destroy ] - - # GET /activities or /activities.json - def index - @activities = Activity.all - end - - # GET /activities/1 or /activities/1.json - def show - end - - # GET /activities/new - def new - @activity = Activity.new - end - - # GET /activities/1/edit - def edit - end - - # POST /activities or /activities.json - def create - @activity = Activity.new(activity_params) - - respond_to do |format| - if @activity.save - format.html { redirect_to activity_url(@activity), notice: "Activity was successfully created." } - format.json { render :show, status: :created, location: @activity } - else - format.html { render :new, status: :unprocessable_entity } - format.json { render json: @activity.errors, status: :unprocessable_entity } - end - end - end - - # PATCH/PUT /activities/1 or /activities/1.json - def update - respond_to do |format| - if @activity.update(activity_params) - format.html { redirect_to activity_url(@activity), notice: "Activity was successfully updated." } - format.json { render :show, status: :ok, location: @activity } - else - format.html { render :edit, status: :unprocessable_entity } - format.json { render json: @activity.errors, status: :unprocessable_entity } - end - end - end - - # DELETE /activities/1 or /activities/1.json - def destroy - @activity.destroy - - respond_to do |format| - format.html { redirect_to activities_url, notice: "Activity was successfully destroyed." } - format.json { head :no_content } - end - end - - private - # Use callbacks to share common setup or constraints between actions. - def set_activity - @activity = Activity.find(params[:id]) - end - - # Only allow a list of trusted parameters through. - def activity_params - params.require(:activity).permit(:title, :activity_type, :start, :duration, :calories) - end -end diff --git a/week_4/activity-tracker/app/helpers/activities_helper.rb b/week_4/activity-tracker/app/helpers/activities_helper.rb deleted file mode 100644 index 4e9784cc..00000000 --- a/week_4/activity-tracker/app/helpers/activities_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module ActivitiesHelper -end diff --git a/week_4/activity-tracker/app/models/activity.rb b/week_4/activity-tracker/app/models/activity.rb deleted file mode 100644 index a99f990d..00000000 --- a/week_4/activity-tracker/app/models/activity.rb +++ /dev/null @@ -1,2 +0,0 @@ -class Activity < ApplicationRecord -end diff --git a/week_4/activity-tracker/app/views/activities/_activity.html.erb b/week_4/activity-tracker/app/views/activities/_activity.html.erb deleted file mode 100644 index aab462e3..00000000 --- a/week_4/activity-tracker/app/views/activities/_activity.html.erb +++ /dev/null @@ -1,27 +0,0 @@ -
-

- Title: - <%= activity.title %> -

- -

- Activity type: - <%= activity.activity_type %> -

- -

- Start: - <%= activity.start %> -

- -

- Duration: - <%= activity.duration %> -

- -

- Calories: - <%= activity.calories %> -

- -
diff --git a/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder b/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder deleted file mode 100644 index 8efbd331..00000000 --- a/week_4/activity-tracker/app/views/activities/_activity.json.jbuilder +++ /dev/null @@ -1,2 +0,0 @@ -json.extract! activity, :id, :title, :activity_type, :start, :duration, :calories, :created_at, :updated_at -json.url activity_url(activity, format: :json) diff --git a/week_4/activity-tracker/app/views/activities/_form.html.erb b/week_4/activity-tracker/app/views/activities/_form.html.erb deleted file mode 100644 index 6d4079c4..00000000 --- a/week_4/activity-tracker/app/views/activities/_form.html.erb +++ /dev/null @@ -1,42 +0,0 @@ -<%= form_with(model: activity) do |form| %> - <% if activity.errors.any? %> -
-

<%= pluralize(activity.errors.count, "error") %> prohibited this activity from being saved:

- -
    - <% activity.errors.each do |error| %> -
  • <%= error.full_message %>
  • - <% end %> -
-
- <% end %> - -
- <%= form.label :title, style: "display: block" %> - <%= form.text_field :title %> -
- -
- <%= form.label :activity_type, style: "display: block" %> - <%= form.text_field :activity_type %> -
- -
- <%= form.label :start, style: "display: block" %> - <%= form.datetime_field :start %> -
- -
- <%= form.label :duration, style: "display: block" %> - <%= form.text_field :duration %> -
- -
- <%= form.label :calories, style: "display: block" %> - <%= form.number_field :calories %> -
- -
- <%= form.submit %> -
-<% end %> diff --git a/week_4/activity-tracker/app/views/activities/edit.html.erb b/week_4/activity-tracker/app/views/activities/edit.html.erb deleted file mode 100644 index 4774a05e..00000000 --- a/week_4/activity-tracker/app/views/activities/edit.html.erb +++ /dev/null @@ -1,10 +0,0 @@ -

Editing activity

- -<%= render "form", activity: @activity %> - -
- -
- <%= link_to "Show this activity", @activity %> | - <%= link_to "Back to activities", activities_path %> -
diff --git a/week_4/activity-tracker/app/views/activities/index.html.erb b/week_4/activity-tracker/app/views/activities/index.html.erb deleted file mode 100644 index 776f9042..00000000 --- a/week_4/activity-tracker/app/views/activities/index.html.erb +++ /dev/null @@ -1,14 +0,0 @@ -

<%= notice %>

- -

Activities

- -
- <% @activities.each do |activity| %> - <%= render activity %> -

- <%= link_to "Show this activity", activity %> -

- <% end %> -
- -<%= link_to "New activity", new_activity_path %> diff --git a/week_4/activity-tracker/app/views/activities/index.json.jbuilder b/week_4/activity-tracker/app/views/activities/index.json.jbuilder deleted file mode 100644 index 865f89ee..00000000 --- a/week_4/activity-tracker/app/views/activities/index.json.jbuilder +++ /dev/null @@ -1 +0,0 @@ -json.array! @activities, partial: "activities/activity", as: :activity diff --git a/week_4/activity-tracker/app/views/activities/new.html.erb b/week_4/activity-tracker/app/views/activities/new.html.erb deleted file mode 100644 index 855a5899..00000000 --- a/week_4/activity-tracker/app/views/activities/new.html.erb +++ /dev/null @@ -1,9 +0,0 @@ -

New activity

- -<%= render "form", activity: @activity %> - -
- -
- <%= link_to "Back to activities", activities_path %> -
diff --git a/week_4/activity-tracker/app/views/activities/show.html.erb b/week_4/activity-tracker/app/views/activities/show.html.erb deleted file mode 100644 index 73be1e19..00000000 --- a/week_4/activity-tracker/app/views/activities/show.html.erb +++ /dev/null @@ -1,10 +0,0 @@ -

<%= notice %>

- -<%= render @activity %> - -
- <%= link_to "Edit this activity", edit_activity_path(@activity) %> | - <%= link_to "Back to activities", activities_path %> - - <%= button_to "Destroy this activity", @activity, method: :delete %> -
diff --git a/week_4/activity-tracker/app/views/activities/show.json.jbuilder b/week_4/activity-tracker/app/views/activities/show.json.jbuilder deleted file mode 100644 index a145d0a8..00000000 --- a/week_4/activity-tracker/app/views/activities/show.json.jbuilder +++ /dev/null @@ -1 +0,0 @@ -json.partial! "activities/activity", activity: @activity diff --git a/week_4/activity-tracker/app/views/activities/stats.html.erb b/week_4/activity-tracker/app/views/activities/stats.html.erb deleted file mode 100644 index e69de29b..00000000 diff --git a/week_4/activity-tracker/config/routes.rb b/week_4/activity-tracker/config/routes.rb index 9ee203b2..7ff20da4 100644 --- a/week_4/activity-tracker/config/routes.rb +++ b/week_4/activity-tracker/config/routes.rb @@ -1,5 +1,4 @@ Rails.application.routes.draw do - resources :activities # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html diff --git a/week_4/activity-tracker/db/migrate/20230127184553_create_activities.rb b/week_4/activity-tracker/db/migrate/20230127184553_create_activities.rb deleted file mode 100644 index d0fe3b06..00000000 --- a/week_4/activity-tracker/db/migrate/20230127184553_create_activities.rb +++ /dev/null @@ -1,13 +0,0 @@ -class CreateActivities < ActiveRecord::Migration[7.0] - def change - create_table :activities do |t| - t.string :title - t.string :activity_type - t.datetime :start - t.decimal :duration - t.integer :calories - - t.timestamps - end - end -end diff --git a/week_4/activity-tracker/db/schema.rb b/week_4/activity-tracker/db/schema.rb index 8543cda3..a3b04951 100644 --- a/week_4/activity-tracker/db/schema.rb +++ b/week_4/activity-tracker/db/schema.rb @@ -10,15 +10,5 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.0].define(version: 2023_01_27_184553) do - create_table "activities", force: :cascade do |t| - t.string "title" - t.string "activity_type" - t.datetime "start" - t.decimal "duration" - t.integer "calories" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - end - +ActiveRecord::Schema[7.0].define(version: 0) do end diff --git a/week_4/activity-tracker/test/fixtures/activities.yml b/week_4/activity-tracker/test/fixtures/activities.yml deleted file mode 100644 index aff553eb..00000000 --- a/week_4/activity-tracker/test/fixtures/activities.yml +++ /dev/null @@ -1,15 +0,0 @@ -# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -one: - title: MyString - activity_type: MyString - start: 2023-01-28 00:15:53 - duration: 9.99 - calories: 1 - -two: - title: MyString - activity_type: MyString - start: 2023-01-28 00:15:53 - duration: 9.99 - calories: 1 diff --git a/week_4/activity-tracker/test/models/activity_test.rb b/week_4/activity-tracker/test/models/activity_test.rb deleted file mode 100644 index c07a8b91..00000000 --- a/week_4/activity-tracker/test/models/activity_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require "test_helper" - -class ActivityTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/week_4/activity-tracker/test/system/activities_test.rb b/week_4/activity-tracker/test/system/activities_test.rb deleted file mode 100644 index 15feb5a2..00000000 --- a/week_4/activity-tracker/test/system/activities_test.rb +++ /dev/null @@ -1,49 +0,0 @@ -require "application_system_test_case" - -class ActivitiesTest < ApplicationSystemTestCase - setup do - @activity = activities(:one) - end - - test "visiting the index" do - visit activities_url - assert_selector "h1", text: "Activities" - end - - test "should create activity" do - visit activities_url - click_on "New activity" - - fill_in "Activity type", with: @activity.activity_type - fill_in "Calories", with: @activity.calories - fill_in "Duration", with: @activity.duration - fill_in "Start", with: @activity.start - fill_in "Title", with: @activity.title - click_on "Create Activity" - - assert_text "Activity was successfully created" - click_on "Back" - end - - test "should update Activity" do - visit activity_url(@activity) - click_on "Edit this activity", match: :first - - fill_in "Activity type", with: @activity.activity_type - fill_in "Calories", with: @activity.calories - fill_in "Duration", with: @activity.duration - fill_in "Start", with: @activity.start - fill_in "Title", with: @activity.title - click_on "Update Activity" - - assert_text "Activity was successfully updated" - click_on "Back" - end - - test "should destroy Activity" do - visit activity_url(@activity) - click_on "Destroy this activity", match: :first - - assert_text "Activity was successfully destroyed" - end -end From 4d5fba37c18aadeaa931da35f4ced30aed775a59 Mon Sep 17 00:00:00 2001 From: Parth Mittal <76661350+mittal-parth@users.noreply.github.com> Date: Mon, 30 Jan 2023 11:23:50 +0530 Subject: [PATCH 10/13] Week-4: Add logs, more controller info and screenshots --- week_4/activity-tracker/README.md | 113 +++++++++++++++++++++++++++++- 1 file changed, 112 insertions(+), 1 deletion(-) diff --git a/week_4/activity-tracker/README.md b/week_4/activity-tracker/README.md index c3248fd1..d97ac306 100644 --- a/week_4/activity-tracker/README.md +++ b/week_4/activity-tracker/README.md @@ -64,6 +64,23 @@ Ensure that you have created the database using `rails db:create`. You can now a Run the server using `rails server`. If you now go to `localhost:3000/activities` on your browser, you can see a basic app in function! +image + +Feel free to play around with the app now. Here are some screenshots of what you should be able to see: + +image + +_New Activity_ + +image + +_Show activity_ + +image + +_Editing an activity_ + + ## The Controller Now, lets open the controller and see what is happening. We'll take an example of a simple function, and try to understand what is happening. @@ -82,6 +99,100 @@ If you notice, the variable starts with `@`. This is a special type of variable At the end, we do not tell Rails to render any particular template (in opposition to some other frameworks, for instance Django). This is because of how Rails works - convention over configuration. Rails will automatically look for a file with the name `index.html` or `index.html.erb` (you'll learn about the `.erb` format when you learn about views), and directly render that file. Pretty convenient, right? +### Other important actions + +- `before_action`: A callback that sets the @activity instance variable with the Activity model instance, based on the id passed in the URL, before executing show, edit, update, and destroy actions. + +- `show` action: Displays the information of a single Activity instance, stored in the @activity instance variable. (GET Request) + +- `new` action: Creates a new instance of the Activity model, stored in the @activity instance variable. (GET Request) + +- `edit` action: Edits an existing Activity instance, stored in the @activity instance variable. (GET Request) + +- `create` action: Creates a new Activity instance with the parameters passed from the form, stored in the @activity instance variable. If the save is successful, it redirects to the show view with a success message, otherwise it renders the new view with an error message. (POST Request) + +```ruby + + def create + @activity = Activity.new(activity_params) + + respond_to do |format| + if @activity.save + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully created." } + format.json { render :show, status: :created, location: @activity } + else + format.html { render :new, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + +``` + +- `update` action: Updates an existing Activity instance with the parameters passed from the form, stored in the @activity instance variable. If the update is successful, it redirects to the show view with a success message, otherwise it renders the edit view with an error message. (PUT/PATCH Request) + +```ruby + + def update + respond_to do |format| + if @activity.update(activity_params) + format.html { redirect_to activity_url(@activity), notice: "Activity was successfully updated." } + format.json { render :show, status: :ok, location: @activity } + else + format.html { render :edit, status: :unprocessable_entity } + format.json { render json: @activity.errors, status: :unprocessable_entity } + end + end + end + +``` + +- `destroy` action: Destroys an existing Activity instance, stored in the @activity instance variable. It then redirects to the index view with a success message. (DELETE Request) + +```ruby + + def destroy + @activity.destroy + + respond_to do |format| + format.html { redirect_to activities_url, notice: "Activity was successfully destroyed." } + format.json { head :no_content } + end + end + +``` + +- `set_activity` private method: Sets the @activity instance variable based on the id passed in the URL. + +- `activity_params` private method: Strong parameters method, allows only the title, activity_type, start, duration, and calories attributes to be passed as parameters to the Activity model. + +image + + +## Looking at the logs + +Logs are useful to debug the application and display information about what is happening (as they 'log' everything). They can be viewed in the terminal where you ran `rails server`. + +Lets understand one such log. Others follow a similar pattern and can be explored on your own. + +image + +This is generated when you try to edit an activity. + +- The first line indicates that it has started the "PATCH" method for the _route_ `/activites/1`. + +- Processing by `ActivitiesController#update` indicates that the request is being processed by the `ActivitiesController`'s `update` action. + +- The next line indicates all the paramters being passed. This is the body of an HTTP Request. It contains all the information of our activity. + +- `set_activity` is run as a before action to find the mathing activity. + +- `UPDATE "activities" SET "calories" = ?....` indicates that an SQL `UPDATE` query is run to update our activity in the database. + +- `Redirected to https://mittal-parth-zany-space-engine-6pvjx5rjx743pwp-3000.preview.app.github.dev/activities/1` indicates that after successful updation of the record, the user has been redirected to `/activities/1` (showing the activity) + +- `Completed 302` indicates the status code of the response. 302 as you'd recall stands for redirect. + ## `rails generate controller` Scaffolding is an extremely easy and powerful way to bring up your resources. However, this is not the only way you can create controllers. They can also be generated normally by @@ -148,4 +259,4 @@ Not providing `to:` will tell Rails to look for a action with the same name as t ## References - [Rails Routing from the Outside In](https://guides.rubyonrails.org/routing.html) - [Action Controllers](https://guides.rubyonrails.org/action_controller_overview.html) -- [Layouts and Rendering in Rails (Views)](https://guides.rubyonrails.org/layouts_and_rendering.html) \ No newline at end of file +- [Layouts and Rendering in Rails (Views)](https://guides.rubyonrails.org/layouts_and_rendering.html) From d6997b7ae3085b45edf8ab464e246fdaa9fff2dc Mon Sep 17 00:00:00 2001 From: Parth Mittal <76661350+mittal-parth@users.noreply.github.com> Date: Sun, 5 Feb 2023 19:33:40 +0530 Subject: [PATCH 11/13] Add week 4 link --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index aa3fc22b..ecc06009 100644 --- a/README.md +++ b/README.md @@ -24,5 +24,9 @@ create a new Rails project and build a simple website. Later we will take a closer look at Model of the MVC Architecture and talk about databases and working with records. +## [Week 4 - Controllers and Authentication](/week_4) + +This week, we will look into controllers, routing and authentication. + ## Contact In case of doubts related to the Bootcamp, feel free to reach out to the mentors on the [**#doubts**](https://discord.com/channels/1052463702558908416/1052467811143913552) channel on [Discord](https://discord.gg/HQKpB6XH). From 3727ee510c9fc3f500cec63ee910594a39adab4d Mon Sep 17 00:00:00 2001 From: Parth Mittal <76661350+mittal-parth@users.noreply.github.com> Date: Tue, 7 Feb 2023 15:30:44 +0530 Subject: [PATCH 12/13] Week 5 Resources (#121) * add initial week-5 content * add readme * add readme, dark-mode and screenshots * add devise * update readme with week-5 link --- README.md | 9 +- week_5/README.md | 548 +++++++++++ week_5/activity-tracker/.ruby-version | 1 + week_5/activity-tracker/.tool-versions | 2 + week_5/activity-tracker/Gemfile | 78 ++ week_5/activity-tracker/Gemfile.lock | 270 ++++++ week_5/activity-tracker/README.md | 262 +++++ week_5/activity-tracker/Rakefile | 6 + .../app/assets/config/manifest.js | 4 + .../activity-tracker/app/assets/images/.keep | 0 .../app/assets/stylesheets/application.scss | 15 + .../app/assets/stylesheets/dark-mode.css | 900 ++++++++++++++++++ .../app/channels/application_cable/channel.rb | 4 + .../channels/application_cable/connection.rb | 4 + .../app/controllers/activities_controller.rb | 70 ++ .../app/controllers/application_controller.rb | 2 + .../app/controllers/concerns/.keep | 0 .../app/helpers/activities_helper.rb | 2 + .../app/helpers/application_helper.rb | 2 + .../app/javascript/application.js | 3 + .../app/javascript/controllers/application.js | 9 + .../controllers/hello_controller.js | 7 + .../app/javascript/controllers/index.js | 11 + .../app/jobs/application_job.rb | 7 + .../app/mailers/application_mailer.rb | 4 + .../activity-tracker/app/models/activity.rb | 2 + .../app/models/application_record.rb | 3 + .../app/models/concerns/.keep | 0 .../app/views/activities/_activity.html.erb | 27 + .../views/activities/_activity.json.jbuilder | 2 + .../app/views/activities/_form.html.erb | 42 + .../app/views/activities/edit.html.erb | 10 + .../app/views/activities/index.html.erb | 14 + .../app/views/activities/index.json.jbuilder | 1 + .../app/views/activities/new.html.erb | 9 + .../app/views/activities/show.html.erb | 10 + .../app/views/activities/show.json.jbuilder | 1 + .../app/views/layouts/application.html.erb | 18 + .../app/views/layouts/mailer.html.erb | 13 + .../app/views/layouts/mailer.text.erb | 1 + week_5/activity-tracker/authentication.md | 31 + week_5/activity-tracker/bin/bundle | 114 +++ week_5/activity-tracker/bin/importmap | 4 + week_5/activity-tracker/bin/rails | 4 + week_5/activity-tracker/bin/rake | 4 + week_5/activity-tracker/bin/setup | 33 + week_5/activity-tracker/config.ru | 6 + week_5/activity-tracker/config/application.rb | 22 + week_5/activity-tracker/config/boot.rb | 4 + week_5/activity-tracker/config/cable.yml | 10 + .../config/credentials.yml.enc | 1 + week_5/activity-tracker/config/database.yml | 25 + week_5/activity-tracker/config/environment.rb | 5 + .../config/environments/development.rb | 74 ++ .../config/environments/production.rb | 93 ++ .../config/environments/test.rb | 60 ++ week_5/activity-tracker/config/importmap.rb | 7 + .../config/initializers/assets.rb | 12 + .../initializers/content_security_policy.rb | 25 + .../config/initializers/devise.rb | 311 ++++++ .../initializers/filter_parameter_logging.rb | 8 + .../config/initializers/inflections.rb | 16 + .../config/initializers/permissions_policy.rb | 11 + .../config/locales/devise.en.yml | 65 ++ week_5/activity-tracker/config/locales/en.yml | 33 + week_5/activity-tracker/config/master.key | 1 + week_5/activity-tracker/config/puma.rb | 43 + week_5/activity-tracker/config/routes.rb | 8 + week_5/activity-tracker/config/storage.yml | 34 + .../20230205151240_create_activities.rb | 13 + week_5/activity-tracker/db/schema.rb | 24 + week_5/activity-tracker/db/seeds.rb | 7 + week_5/activity-tracker/lib/assets/.keep | 0 week_5/activity-tracker/lib/tasks/.keep | 0 week_5/activity-tracker/public/404.html | 67 ++ week_5/activity-tracker/public/422.html | 67 ++ week_5/activity-tracker/public/500.html | 66 ++ .../public/apple-touch-icon-precomposed.png | 0 .../public/apple-touch-icon.png | 0 week_5/activity-tracker/public/favicon.ico | 0 week_5/activity-tracker/public/robots.txt | 1 + week_5/activity-tracker/storage/.keep | 0 .../test/application_system_test_case.rb | 5 + .../application_cable/connection_test.rb | 11 + .../activity-tracker/test/controllers/.keep | 0 .../controllers/activities_controller_test.rb | 48 + .../test/fixtures/activities.yml | 15 + .../test/fixtures/files/.keep | 0 week_5/activity-tracker/test/helpers/.keep | 0 .../activity-tracker/test/integration/.keep | 0 week_5/activity-tracker/test/mailers/.keep | 0 week_5/activity-tracker/test/models/.keep | 0 .../test/models/activity_model_test.rb | 23 + .../test/models/activity_test.rb | 7 + week_5/activity-tracker/test/system/.keep | 0 .../test/system/activities_test.rb | 49 + week_5/activity-tracker/test/test_helper.rb | 13 + week_5/activity-tracker/vendor/.keep | 0 .../activity-tracker/vendor/javascript/.keep | 0 week_5/screenshots/activity-tracker-views.jpg | Bin 0 -> 16040 bytes week_5/screenshots/form.jpg | Bin 0 -> 71897 bytes week_5/screenshots/index.jpg | Bin 0 -> 83357 bytes week_5/screenshots/navbar.jpg | Bin 0 -> 52132 bytes week_5/screenshots/project_directory.jpg | Bin 0 -> 8413 bytes week_5/screenshots/shared.jpg | Bin 0 -> 5453 bytes 105 files changed, 3851 insertions(+), 2 deletions(-) create mode 100644 week_5/README.md create mode 100644 week_5/activity-tracker/.ruby-version create mode 100644 week_5/activity-tracker/.tool-versions create mode 100644 week_5/activity-tracker/Gemfile create mode 100644 week_5/activity-tracker/Gemfile.lock create mode 100644 week_5/activity-tracker/README.md create mode 100644 week_5/activity-tracker/Rakefile create mode 100644 week_5/activity-tracker/app/assets/config/manifest.js create mode 100644 week_5/activity-tracker/app/assets/images/.keep create mode 100644 week_5/activity-tracker/app/assets/stylesheets/application.scss create mode 100644 week_5/activity-tracker/app/assets/stylesheets/dark-mode.css create mode 100644 week_5/activity-tracker/app/channels/application_cable/channel.rb create mode 100644 week_5/activity-tracker/app/channels/application_cable/connection.rb create mode 100644 week_5/activity-tracker/app/controllers/activities_controller.rb create mode 100644 week_5/activity-tracker/app/controllers/application_controller.rb create mode 100644 week_5/activity-tracker/app/controllers/concerns/.keep create mode 100644 week_5/activity-tracker/app/helpers/activities_helper.rb create mode 100644 week_5/activity-tracker/app/helpers/application_helper.rb create mode 100644 week_5/activity-tracker/app/javascript/application.js create mode 100644 week_5/activity-tracker/app/javascript/controllers/application.js create mode 100644 week_5/activity-tracker/app/javascript/controllers/hello_controller.js create mode 100644 week_5/activity-tracker/app/javascript/controllers/index.js create mode 100644 week_5/activity-tracker/app/jobs/application_job.rb create mode 100644 week_5/activity-tracker/app/mailers/application_mailer.rb create mode 100644 week_5/activity-tracker/app/models/activity.rb create mode 100644 week_5/activity-tracker/app/models/application_record.rb create mode 100644 week_5/activity-tracker/app/models/concerns/.keep create mode 100644 week_5/activity-tracker/app/views/activities/_activity.html.erb create mode 100644 week_5/activity-tracker/app/views/activities/_activity.json.jbuilder create mode 100644 week_5/activity-tracker/app/views/activities/_form.html.erb create mode 100644 week_5/activity-tracker/app/views/activities/edit.html.erb create mode 100644 week_5/activity-tracker/app/views/activities/index.html.erb create mode 100644 week_5/activity-tracker/app/views/activities/index.json.jbuilder create mode 100644 week_5/activity-tracker/app/views/activities/new.html.erb create mode 100644 week_5/activity-tracker/app/views/activities/show.html.erb create mode 100644 week_5/activity-tracker/app/views/activities/show.json.jbuilder create mode 100644 week_5/activity-tracker/app/views/layouts/application.html.erb create mode 100644 week_5/activity-tracker/app/views/layouts/mailer.html.erb create mode 100644 week_5/activity-tracker/app/views/layouts/mailer.text.erb create mode 100644 week_5/activity-tracker/authentication.md create mode 100755 week_5/activity-tracker/bin/bundle create mode 100755 week_5/activity-tracker/bin/importmap create mode 100755 week_5/activity-tracker/bin/rails create mode 100755 week_5/activity-tracker/bin/rake create mode 100755 week_5/activity-tracker/bin/setup create mode 100644 week_5/activity-tracker/config.ru create mode 100644 week_5/activity-tracker/config/application.rb create mode 100644 week_5/activity-tracker/config/boot.rb create mode 100644 week_5/activity-tracker/config/cable.yml create mode 100644 week_5/activity-tracker/config/credentials.yml.enc create mode 100644 week_5/activity-tracker/config/database.yml create mode 100644 week_5/activity-tracker/config/environment.rb create mode 100644 week_5/activity-tracker/config/environments/development.rb create mode 100644 week_5/activity-tracker/config/environments/production.rb create mode 100644 week_5/activity-tracker/config/environments/test.rb create mode 100644 week_5/activity-tracker/config/importmap.rb create mode 100644 week_5/activity-tracker/config/initializers/assets.rb create mode 100644 week_5/activity-tracker/config/initializers/content_security_policy.rb create mode 100644 week_5/activity-tracker/config/initializers/devise.rb create mode 100644 week_5/activity-tracker/config/initializers/filter_parameter_logging.rb create mode 100644 week_5/activity-tracker/config/initializers/inflections.rb create mode 100644 week_5/activity-tracker/config/initializers/permissions_policy.rb create mode 100644 week_5/activity-tracker/config/locales/devise.en.yml create mode 100644 week_5/activity-tracker/config/locales/en.yml create mode 100644 week_5/activity-tracker/config/master.key create mode 100644 week_5/activity-tracker/config/puma.rb create mode 100644 week_5/activity-tracker/config/routes.rb create mode 100644 week_5/activity-tracker/config/storage.yml create mode 100644 week_5/activity-tracker/db/migrate/20230205151240_create_activities.rb create mode 100644 week_5/activity-tracker/db/schema.rb create mode 100644 week_5/activity-tracker/db/seeds.rb create mode 100644 week_5/activity-tracker/lib/assets/.keep create mode 100644 week_5/activity-tracker/lib/tasks/.keep create mode 100644 week_5/activity-tracker/public/404.html create mode 100644 week_5/activity-tracker/public/422.html create mode 100644 week_5/activity-tracker/public/500.html create mode 100644 week_5/activity-tracker/public/apple-touch-icon-precomposed.png create mode 100644 week_5/activity-tracker/public/apple-touch-icon.png create mode 100644 week_5/activity-tracker/public/favicon.ico create mode 100644 week_5/activity-tracker/public/robots.txt create mode 100644 week_5/activity-tracker/storage/.keep create mode 100644 week_5/activity-tracker/test/application_system_test_case.rb create mode 100644 week_5/activity-tracker/test/channels/application_cable/connection_test.rb create mode 100644 week_5/activity-tracker/test/controllers/.keep create mode 100644 week_5/activity-tracker/test/controllers/activities_controller_test.rb create mode 100644 week_5/activity-tracker/test/fixtures/activities.yml create mode 100644 week_5/activity-tracker/test/fixtures/files/.keep create mode 100644 week_5/activity-tracker/test/helpers/.keep create mode 100644 week_5/activity-tracker/test/integration/.keep create mode 100644 week_5/activity-tracker/test/mailers/.keep create mode 100644 week_5/activity-tracker/test/models/.keep create mode 100644 week_5/activity-tracker/test/models/activity_model_test.rb create mode 100644 week_5/activity-tracker/test/models/activity_test.rb create mode 100644 week_5/activity-tracker/test/system/.keep create mode 100644 week_5/activity-tracker/test/system/activities_test.rb create mode 100644 week_5/activity-tracker/test/test_helper.rb create mode 100644 week_5/activity-tracker/vendor/.keep create mode 100644 week_5/activity-tracker/vendor/javascript/.keep create mode 100644 week_5/screenshots/activity-tracker-views.jpg create mode 100644 week_5/screenshots/form.jpg create mode 100644 week_5/screenshots/index.jpg create mode 100644 week_5/screenshots/navbar.jpg create mode 100644 week_5/screenshots/project_directory.jpg create mode 100644 week_5/screenshots/shared.jpg diff --git a/README.md b/README.md index ecc06009..598c9fe9 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ We have provided three ways of setting up a development environment, and [Dev Container](/setup/dev_container.md). We recommend you to choose [GitHub codespaces](/setup/github_codespaces.md) if you face any issues while installing ruby [locally](/setup/local_setup.md). -> We recommend sticking to the versions mentioned in the Installation Guide and -> run commands exactly as instructed, as all assignments in this Bootcamp are +> We recommend sticking to the versions mentioned in the Installation Guide and +> run commands exactly as instructed, as all assignments in this Bootcamp are > tested with these versions. ## [Week 1 - HTML and CSS](/week_1) @@ -28,5 +28,10 @@ Later we will take a closer look at Model of the MVC Architecture and talk about This week, we will look into controllers, routing and authentication. +## [Week 5 - Views](/week_4) + +So after 4 weeks, we have our basic app ready! 🥳 +However, there is one problem. It looks 🥴. Lets fix that! We'll now style our application using [Bootstrap](https://getbootstrap.com/docs/5.0/getting-started/introduction/) and look at the _View_ layer which is responsible for presenting data appropriately. + ## Contact In case of doubts related to the Bootcamp, feel free to reach out to the mentors on the [**#doubts**](https://discord.com/channels/1052463702558908416/1052467811143913552) channel on [Discord](https://discord.gg/HQKpB6XH). diff --git a/week_5/README.md b/week_5/README.md new file mode 100644 index 00000000..f0090615 --- /dev/null +++ b/week_5/README.md @@ -0,0 +1,548 @@ +# Week 5 - Views + +So after 4 weeks, we have our basic app ready! 🥳 +However, there is one problem. It looks 🥴. Lets fix that! We'll now style our application using [Bootstrap](https://getbootstrap.com/docs/5.0/getting-started/introduction/) and look at the _View_ layer which is responsible for presenting data appropriately. + +In a Rails application, the views are stored in app/views folder. +Each controller has their own views and the name of view file must match the action name _exactly_. Depending on the action executed, the views are used. + +## Views as HTML Files + +At a basic level, views are HTML files in which we insert information +from our controllers. As views are HTML files, anything that works in +HTML, CSS and Javascript works here. If you need a refresher 👇🏻 + +- [HTML Tutorial](https://github.com/IRIS-NITK/IRIS-RoR-Bootcamp-2022/blob/main/week_1/HTML.md) +- [CSS Tutorial](https://github.com/IRIS-NITK/IRIS-RoR-Bootcamp-2022/blob/main/week_1/CSS.md) + +## Bootstrap + +Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. It contains HTML, CSS and JavaScript-based design templates for typography, forms, buttons, navigation, and other interface components. + +> Why you ask? +> We could write all of our styling on our own but thats hard and time consuming. + + +### Installing Bootstrap + +> **We have already done this for you but this is so that you know how to do it later** + +Under the `activity-tracker` go to the `Gemfile` and add the Bootstrap Ruby gem by pasting the following code at the end of the file. + +``` +gem 'bootstrap', '~> 5.2.2' +``` + +On the terminal run `bundle install` + +Rename `app/assets/stylesheets/application.css` to `app/assets/stylesheets/application.scss`: and import Bootstrap styles by adding: + +``` +@import "bootstrap"; +``` + +You are all set and you should now see slightly different styling! 🚀 + +> Reference: [Installing Bootstrap Gem and jQuery in Rails](https://github.com/twbs/bootstrap-rubygem/blob/main/README.md) + +## Let's Style + +> Throughout this section, I will add some styling while also explaning View concepts + +> Note: The dark-mode.css file has already been added in `/app/assets/stylesheets` which adds the theme and the colour shceme for the project. + +> Bootstrap Icons have also been added for ease + +### Understanding the project directory + +![Project Directory](screenshots/project_directory.jpg) + +- The `activity` folder contains all the view files related to the `Activity` Model. This would be repeated for all the other models you'd make in an application. + + Using Scaffolds, Rails creates even the view files for all basic actions including `index`, `show`, `edit`, `create` and `delete`! 🤯 + + ![Activity Tracker Views Folder](screenshots/activity-tracker-views.jpg) + +- The `layouts` folder contains the base layouts for differrent formats which are inhereted in all other view files. For HTML files, `application.html.erb` is used as a base everywhere else + + ```erb + + + + + ActivityTracker + + <%# %> + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= stylesheet_link_tag "dark-mode", "data-turbo-track": "reload" %> + + + <%= javascript_importmap_tags %> + + + + <%= yield %> + + + + ``` + +## Partials and Navbar + +When writing Ruby, we break up complex methods into multiple, smaller methods. Likewise, when writing views, we break up complex view files into smaller partials. + +- The partials are named with the leading underscore and are in the same directory as the original view. +- You can pass variables to partials using locals keyword. + +Since the Navbar will be used at all places and can be repetitive, we will create a navbar partial. + +- Create a `shared` folder inside the `views` folder + + ![Navbar](screenshots/shared.jpg) + +- Create a file named `_navbar.html.erb` inside and paste the following code. We'll be using the Bootstrap Navbar component for this + + ```erb + + + + ``` + +- Now we need to reference this navbar so that Rails knows how to serve it. +- Inside `application.html.erb`, use `<%= render partial: 'shared/navbar' %>` to render the navbar partial. +- We have also wrapped the `<%= yield %>` tag inside a container to give the entire layout some margin and padding. + + ```erb + + + <%= render partial: 'shared/navbar' %> +
+ <%= yield %> +
+ + + ``` + +> Note that we dont use shared/_navbar. Rails is smart enough to know that since its a partial, it will begin with _! + +![Navbar](screenshots/navbar.jpg) + +Now it looks better, doesn't it? + + +> Reference and further reading - [Using Partials](https://guides.rubyonrails.org/layouts_and_rendering.html#using-partials) + +## Embedded Ruby + +Embedded Ruby refers to pieces of code in between HTML code, to make the +views dynamic and extensible. + +There are two ways of invoking ERB: +- `<%=` and `%>` wrap Ruby code whose return value will be output in + place of marker. +- `<%` and `%>` wrap Ruby code whose return value will NOT be output. + +``` +# Displays current time +

Page generated at: <%= DateTime.now %>

+ +# Does display not current time +

Page generated at: <% DateTime.now %>

+``` + +The non-returning tag is used for iterating and preparing data: + +```erb +<% @activities.each do |activity| %> + + <%= activity.title %> + <%= activity.calories %> + ... + +<% end %> +``` + +The variables are shared between the controller and views using [instance +variables](https://www.rubyguides.com/2019/07/ruby-instance-variables/), that is variables prefixed by `@`: + +```ruby +class ActivitiesController < ApplicationController + def index + @activities = Activity.all + end +end +``` + +```erb +<% @activities.each do |activity| %> + + <%= activity.title %> + <%= activity.calories %> + ... + +<% end %> +``` + +## Improving Index Page + +We will improve the look of the activities index page using [Bootstrap Card Deck](https://getbootstrap.com/docs/4.0/components/card/#card-decks) component. + +- Style the file using this code + + ```erb + +

<%= notice %>

+ +

+ Activities + <%= link_to "".html_safe, new_activity_path %> +

+ +
+ <% @activities.each do |activity| %> +
+ <%= render activity %> +
+ <% end %> +
+ + ``` +- We have wrapped our `#activities` section inside a `card-deck` and provided a top margin of 4 units. `col-sm-12 col-md-6 col-lg-4` creates a grid of cards which render one in a row on small devices, two in a row on medium devices and three in a row on large devices. + + > Remember the bootstrap grid system? The grid is divided into 12 parts. `col-lg-4` would mean that it would take up only three columns worth space and hence three cards in a row. Similarly with other viewports. + +- We have moved the New Activities button inside the heading and used a plus icon instead using [Bootstrap Icons](https://icons.getbootstrap.com/) (which has already been added by us in `application.html.erb` using the CDN) + +- Another thing you would notice here is the `link_to` helper. + + To make the process of adding hyperlinks easier, Rails provides us with a helper function to generate the markup - `link_to`. + + In plain HTML, you create a link like this: + + ```html + Activities + ``` + + But in Rails that would look like this: + + ```erb + <%= link_to "Activities", activities_path %> + ``` + + _Why?_ 🤔 + + Because we use routes in Rails. + + We want to take advantage of that by using `_path` methods & making that the target (href) of our link. + + Using link_to makes this easier because we don’t have to [interpolate](https://www.rubyguides.com/2019/07/ruby-string-concatenation/) the value. + + > You can see all path methods if you type `rails routes` on the terminal or visit a wrong link in your project + + You can also add classes and other arguments like: + + ```erb + <%= link_to "Activities", activities_path, class: "..." %> + ``` + + - [Further Reading](https://www.rubyguides.com/2019/05/rails-link_to-method/) + +## Improving the Card + +In the last section you would have noticed the use of `<%= render activity %>` which magically renders all our activities. Where is this coming from? The answer is in `_activity.html.erb` + +> Remeber partials? + +- Replace the `_activity.html.erb` code with the following code to style our boring looking cards + +```erb + +
+

<%= activity.title %>

+
+
+
+
<%= activity.activity_type %>
+
+
+
+
+ <%= link_to "".html_safe, edit_activity_path(activity), class: "btn btn-sm btn-secondary" %> +
+
+ <%= button_to "".html_safe, activity, method: :delete, class: "btn btn-sm btn-secondary" %> +
+
+
+
+
+
+
<%= activity.start.in_time_zone.strftime("%d %b, %Y %I:%M %p") %>
+
+
+
+
+
<%= activity.calories %>
+
+
+
<%= activity.duration %>
+
+
+
+
+ +``` + +- The activity variable is passed onto this file from `index.html.erb` and used here. All the attributes of our model (title, activity_type, calories and duration) are now available to us with each acitivity object can be used using the `.` operator. + +- We have used the [Bootstrap Card](https://getbootstrap.com/docs/4.0/components/card/) component, some custom gradients, shadows, padding, margins and the grid system to create this. + +- We have also used Bootstrap icons to add icons + + > Notice the usage of the `link_to` helper for the edit action + +- Another thing you would notice is the `button_to` tag. It works similar to the `link_to` tag and you can read about it more [here](https://apidock.com/rails/v5.2.3/ActionView/Helpers/UrlHelper/button_to) + +- Last thing to note is: + + ```erb + <%= activity.start.in_time_zone.strftime("%d %b, %Y %I:%M %p") %> + ``` + + Rails also provides with helper functions to achieve simple manipulations on `view` data to render it in a nicer fashion. You would see that it now renders the datetime in a more human readable format. + + `strftime` is an inbuilt helper. You can also define your own helpers. You can read about them [here](https://www.rubyguides.com/2020/01/rails-helpers/) + +- With this, our index page now looks like this. How cool is that! 🔥 + +![Index](screenshots/index.jpg) + +## Improving the form + +The HTML form when we are creating or editing an activity is stored in `app/views/activities/_form.html.erb`. Since the file name begins with an underscore, it is a partial. Taking a closer look: + +```erb + +<%= form_with(model: activity) do |form| %> + <% if activity.errors.any? %> +
+

<%= pluralize(activity.errors.count, "error") %> prohibited this activity from being saved:

+ +
    + <% activity.errors.each do |error| %> +
  • <%= error.full_message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= form.label :title, style: "display: block" %> + <%= form.text_field :title %> +
+ +
+ <%= form.label :activity_type, style: "display: block" %> + <%= form.text_field :activity_type %> +
+ +
+ <%= form.label :start, style: "display: block" %> + <%= form.datetime_field :start %> +
+ +
+ <%= form.label :duration, style: "display: block" %> + <%= form.text_field :duration %> +
+ +
+ <%= form.label :calories, style: "display: block" %> + <%= form.number_field :calories %> +
+ +
+ <%= form.submit %> +
+<% end %> + +``` + +- The `form_with` tag takes a model (or a url), fields and generates a +HTML form. For example, by passing the variable `activity` as an local +variable to the partial, Rails figures out whether to create a new +activity or to update an existing activity and pre-fill the forms. + +- The `activity.errors` variable stores any errors that occur during +saving the record. + +- Just like the `link_to` and `button_to`, Rails also has Form Helpers + + `form.label` creates an equivalent `