Ruby Gems To Study 2024
- pg
- rake_tasks
- cane
- rspec
- rspec-rails
- factory_bot
- shoulda-matchers
- faker
- byebug
- yaml_db
- rack-cache
- devise_token_auth
- groupdate
- stripe-rails
- haml
- wicked_pdf
- active_storage_validations
- lockbox
- normalize_country
Working with Postgres SQL
- Connect to the server
-> psql -h mydbserver -U myuser -d mydatabase
-> or: sudo -u postgres psql
-h host: Specifies the hostname or IP address of the PostgreSQL server.
-p port: Specifies the port number (default is 5432).
-U username: Specifies the username to connect with.
-d database: Specifies the database to connect to.1
- To see all databases
-> \l
- Working with a database
-> \c <db name>
- To see all tables
-> \dt
- Describe a table's structure
-> \d table_name
- \ds: List sequences.
- \df: List functions.
- \dv: List views.
- \du: List users.
- To change password
-> ALTER USER user_name WITH PASSWORD 'new_password';
- Rename a db
-> ALTER DATABASE <OLD_NAME> RENAME TO <NEW_NAME>;
- Dump a database
-> pg_dump -h localhost -U huan -d easyweb_production -s > ea.dump
Install Ubuntu subsystem and setup Ruby & Rails
Below are steps to get things done:
1/ To list all distributions
wsl --list --online
2/ To install one:
wsl --install Ubuntu-24.04
When it's ready:
3/ Update the system before installing Ruby
sudo apt update
4/ Now will do install Ruby with RVM
curl -sSL https://get.rvm.io | bash -s stable
rvm install 3.2.5
rvm use 3.2.5 --default
5/ Install Rails
gem install rails
GCP - How to create a Kubernestes cluster
1. Login to GCP and activate Cloud Shell
2. Check and set current project
# Check the current account: gcloud auth list # Check the current project: gcloud config list project # Set the project: gcloud config set project <PROJECT_ID>
3. Enable the container service:
gcloud services enable container.googleapis.com
4. Create your GKE cluster:
gcloud container clusters create cloud-trace-demo --zone=$ZONE
5. Get nodes of the cluster:
kubectl get nodes
Four golden signals that measure a system’s performance and reliability
They are latency, traffic, saturation, and errors.
Load Balancer
Geo-location base LB
URL base LB:
Bucket LB:
GCP Cloud Storage options
These charts are great on making a decision which cloud storage services to use:
Choosing a SQL Database
Database comparisons:
Choosing Spanner?
Linux learning
Create an environment variable: INFRACLASS_REGION=VALUE
Create a sub folder: mkdir XYZ
Create a file: touch FILE or touch folder/FILE
Append the value to file: echo INFRACLASS_REGION=$INFRACLASS_REGION >> ~/infraclass/config
Some commands:
- free : about memory
- sudo dmidecode -t 17 : installed RAM
- nproc : nb of processors
- lscpu : details about CPU installed
GCP Cloud Shell
Work with storage / buckets
To create a new bucket:
gcloud storage buckets create gs://[BUCKET_NAME]
To copy a file to butcket
gcloud storage cp [MY_FILE] gs://[BUCKET_NAME]
Eg: gcloud storage cp 'Stripe integration.txt' gs://huan-testing-0001
Compute Engines
To create a new VM:
gcloud compute instances create mynet-us-vm --machine-type e2-micro --zone europe-west4-c --network manual --image-family debian-12 --image-project debian-cloud
gcloud compute instances create privatenet-us-vm --zone=us-central1-c --machine-type=e2-micro --subnet=privatesubnet-us --image-family=debian-12 --image-project=debian-cloud --boot-disk-size=10GB --boot-disk-type=pd-standard --boot-disk-device-name=privatenet-us-vm
Config project
gcloud config set project VALUE
to set current project_id
Visual Studio history
As of 27/09/2024, the version of VS is 2022
https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-history
Rails working with credentials
1/ To view credentials, use this:
rails credentials:show <environment> <key>
Eg for development: rails credentials:show
2/ To edit credentials:
RAILS_ENV=development VISUAL=nano rails credentials:edit
3/ Now to use the credential:
Rails.application.credentials.stripe_publishable_key
Rails working with Devise for authentication and allow login via Facebook account
1. Generate a new app demo_devise
sudo rails new demo_devise
2. Add new gem into Gemfile and install it
gem "devise"
3. Install devise with this command:
rails g devise:install
4. Generate User model
rails g devise User
Check the migration to uncomment fields for required modules
Check the model User to include required modules
confirmable:
if enabled, after user signed up, he will receive an email also
5. Run migrate db
rails db:migrate
6. Generate home controller with index action
rails g controller home index
7. Adding controller myspace with index action and requires authenticated users
rails g controller myspace index
8. Adding .env file, and gem 'dotenv-rails' into development group
Now try to signup by email address, a new account will be created and can login.
TODO: customize email template
9. Now add Bootstrap into the app
Update importmaps.rb to add new npm packages
pin "popper", to: 'popper.js', preload: true
pin "bootstrap", to: 'bootstrap.min.js', preload: true
10. Update js in application.js
import "popper"
import "bootstrap
10. Add bootstrap gem and its dependency
gem "bootstrap"
gem "sassc-rails"
Then add into application.css
@import "bootstrap";
11. Update manifest.js to add new lines
//= link popper.js
//= link bootstrap.min.js
12. Update HTML page for the layout
13. Add Facebook authentication
We need to create an application, add all required information for Facebook to review.
Then implement the action to handle returned data, and create user in our database.
GCP common commands
GCP Cloud Run:
To list containers:
gcloud run revisions list --region=asia-east1
To delete a container:
gcloud run revisions delete easyweb-00009-q6w --region=asia-east1 --quiet
Deploy Rails application as Production mode
When we deploy a Rails app to a cloud, or even running from a docker image in Production mode, there will be a number of issues could happen. Below is what I encountered:
1/ ArgumentError: Missing `secret_key_base` for 'production' environment, set this string with `bin/rails credentials:edit`
This seems to be a missing key in config/credentials.yml.enc, but actually the is is available. After some digging, I found that when copying the app to build Docker image, we ignored the file /config/master.key
If including that file, the issue fixed, but we shouldn't fix this way.
So we must put the master key as an environment variable. If running a container, the fix can be this way: -e RAILS_MASTER_KEY=<YOUR_KEY>
2/ Set production environment
Can be done by this way: -e RAILS_ENV=production ; when running by docker
3/ Missing application.css file
Ensure that the application.css file exists in the app/assets/stylesheets directory.
Open the config/initializers/assets.rb file and verify the following settings:
Rails.application.config.assets.precompile += %w( application.css )
Then add this into the startup script before starting the server:
rails assets:precompile
4/ Server memory issue.
If running in development/test modes, the ram 256MB is OK, when switching to production, we need to add more RAM, eg 512MB.
2024-09-18 16:36:06.105 ICT
Memory limit of 256 MiB exceeded with 256 MiB used. Consider increasing the memory limit, see https://cloud.google.com/run/docs/configuring/memory-limits
5/ Set number of threads for the server:
Create this ENV variable: RAILS_MAX_THREADS
Deploy application to GCP with Cloud Run
Cloud Run is selected to serve my Rails website.
I build the site as a docker image, and push to Docker Hub private repository.
This post will show all steps to deploy the site to GCP Cloud Run.
1/ Setup GCP account, activate billing and Cloud Run service.
2/ Create an Artifact Repository
So the URL will be as this: asia-southeast1-docker.pkg.dev/<ProjectName>/<RepositoryName>
3/ Build the project and push to Docker Hub (why: in case we can use difference cloud platform, Docker Hub is available also)
4/ Create a PAT token in Docker Hub8
5/ Activate Cloud Shell on GCP (this is free VM for all accounts)
6/ Login to Docker Hub with this command: docker login -u <UserName> -p <YourPAT>
7/ Pull the image from Docker Hub to local cloud shell VM
docker pull <DockerHubImage>
8/ Tag the image to a GCP artifact, like:
docker tag <DockerHubImage> asia-southeast1-docker.pkg.dev/<ProjectName>/<RepositoryName>/easyweb:240918
9/ Push the tag to GCP artifact registry
10/ Go to Cloud Run and deploy a new container
https://console.cloud.google.com/run
11/ Add custom domain, like https://easyweb.abizvn.com/
Git common commands
git rebase <branch_name> : to replay commits of current branch on tip of the branch_name.
git branch -m <new_branch_name> : to rename the current branch name
git reset --hard : to reset working branch to a specific commit. If no commit specified, it reset to HEAD
git reset --hard HEAD^ : to reset working to previous commit. In below screenshot, after running this command, the "Demo commit" will be removed.
ActiveAdmin in an API-only application - step by step
1/ Generate a new app:
rails new apibe_active_admin --api
2/ Adding new gems and bundle
gem 'activeadmin'
gem 'devise' # ActiveAdmin depends on Devise for authentication
gem 'sass-rails' # Required for ActiveAdmin styling
3/ Install devise
rails generate devise:install
4/ Generate user and run migrate
rails generate devise User
rails db:migrate
5/ Install activeadmin
rails generate active_admin:install
Bảo sao các bên bán điện thoại cũ ko lời cao
Nhân tiện tham khảo để mua cái điện thoại mới thay cái cũ hay cu đơ, tìm hiểu chút xem giá mới + giá cũ ra sao.
Giả sử có chiếc iPhone 8 cũ 256GB, còn ngon, họ thu mua < 1.8M. Trong khi tìm mấy chỗ bán dòng này, thì giá khá cao luôn, tầm 5.X triệu. Vậy là lời tầm gần 4M rồi, bao sao ko lãi :D
Working on Rails
Debugging
- byebug: 1) adding them 2) add byebug to break
- debugging-with-the-debug-gem: adding debugger to break, c to continue, q to quit
Test
- simplecov: 1) adding gem 2) Load and launch SimpleCov 3) run the tests 4) open coverage/index.html
Productivity
VS Code plugins for Rails development
Install VS Code by winget:
-> winget install Microsoft.VisualStudioCode
Install Dev Containers
Install Ruby
-> winget install RubyInstallerTeam.Ruby.3.2
Install plugin vscode-icons
DEV common free tools
Modelling
IDE
- Microsoft Visual Studio Code
-> winget install Microsoft.VisualStudioCode - Sublime Text
-> V3: winget install SublimeHQ.SublimeText.3
-> V4: winget install SublimeHQ.SublimeText.4
-> SublimeMerge: winget install SublimeHQ.SublimeMerge
Ruby/Rails
- betterspecs.org - Rails Testing Best Practices
- railsstatuscodes.com - Look up a Rails HTTP Status Code
Giới thiệu dự án LifeTalk
Nơi chia sẻ câu chuyện cuộc sống.
Đảm bảo quyền riêng tư, tế nhị, lịch sự trong mỗi phát ngôn.
RSpec how to very JSON response with params hash
Option 1:
The params hash will be defined as the below
let!(:valid_params) { { event_type: 'income', event_date: Time.now, value: 1000, note: 'update record 2' } }
Then when performing an update (PUT action) we will receive the response in JSON
So we can compare every element of the hash with JSON object
expect(JSON.parse(response.body)["value"]).to eq(valid_params[:value])
expect(JSON.parse(response.body)["note"]).to eq(valid_params[:note])
RSpec::Matchers.define :have_updated_attributes do |expected_attributes|
match do |actual_json|
return false unless actual_json
expected_attributes.all? do |key, value|
if value && (value.is_a?(Time) || value.is_a?(DateTime))
actual_json[key.to_s][0..18] == value.strftime("%Y-%m-%dT%H:%M:%S")
else
actual_json[key.to_s] == value
end
end
end
failure_message do |actual_json|
"expected is: #{expected_attributes} but actual is: #{actual_json}"
end
end
expect(JSON.parse(response.body)).to have_updated_attributes(valid_params)
Test a Rails API application with RSpec
Below are steps to follow
- Adding rspec into the app gemfile:
-> gem 'rspec-rails', '~> 6.1.0' into dev/test group
-> install the gem by running: bundle install
-> run: rspec to verify - Init rspec in the application
-> run this command: rails g rspec:install - Now create a folder /spec/requests
- Create a file called money_records_spec.rb with following
- Run the tests by command: rspec
- Adding FactoryBot to gemfile
-> gem 'factory_bot_rails' into dev/test group
-> bundle install - Now creating a folder /spec/factories, then a file money_records.rb
- Continuing to edit the test file as below
require 'rails_helper'
RSpec.describe 'Money Records API', type: :request do
describe 'GET /money_records' do
it 'returns a list of money records' do
FactoryBot.create(:money_record, event_type: 'income', value: 100, event_date: Time.now, note: 'record 1')
FactoryBot.create(:money_record, event_type: 'income', value: 200, event_date: Time.now, note: 'record 2')
get '/money_records'
expect(response).to have_http_status(:success)
expect(JSON.parse(response.body).size).to eq(2)
end
end
end - Run rspec and verify
Running tests in a Rails API application
Run the tests by following:
rails test test/controllers/money_records_controller_test.rb -v
But getting errors
Error: MoneyRecordsControllerTest#test_should_update_money_record: ActiveRecord::Fixture::FixtureError: table "money_records" has no columns named "type".
This might be an issue with the database - which the model has been changed. Now I run below commands:
RAILS_ENV=test rails db:reset
RAILS_ENV=test rails db:migrate
Actually, the issue is in fixture files & in money_records_controller_test.rb because the model has been updated, changed the "type" to "event_type". Fixed thing this and rerun the test command, all looks fine
rails test test/controllers/money_records_controller_test.rb -v
Running 5 tests in a single process (parallelization threshold is 50)
Run options: -v --seed 36836
# Running:
MoneyRecordsControllerTest#test_should_update_money_record = 2.28 s = .
MoneyRecordsControllerTest#test_should_destroy_money_record = 0.03 s = .
MoneyRecordsControllerTest#test_should_create_money_record = 0.03 s = .
MoneyRecordsControllerTest#test_should_show_money_record = 0.04 s = .
MoneyRecordsControllerTest#test_should_get_index = 0.04 s = .
Finished in 2.452687s, 2.0386 runs/s, 3.6694 assertions/s.
5 runs, 9 assertions, 0 failures, 0 errors, 0 skips
Create MoneyRecording API with Rails
Below is the detail of MoneyRecording API with Rails
Testing Guidelines when you are a developer
- If your code is hard to test, it's probably the bad code
- Tests will need to be written for all new code
- Tests will need to be written for all changed code
- Tests will be important equally to the code to be tested
صباح الخير يوم جديد
This is a test post, the title in English is "Good morning new day".
We will see how this title in Arabic will be used for the friendly id.
So after submitted, the url to this post is "https://easyweb-lifetalk.onrender.com/posts/-240729-0141" - it means that the Arabic title couldn't be translated into a friendly one.
Tips to work with render.com free tier
Free tier services on render.com will be down after 15 minutes of inactivity.
So to make it up and running, what I will do is as below:
- Setup a monitoring solution using uptime-kuma
- In this site, make it running and monitor the site itself for every 5 minutes
- Deploy other service on difference account, one account for one service only
- Adding a monitoring in uptime-kuma to make it not idle
Happy deploying :) - this is just for hobby purpose, as the free instances are very small.
Free Ruby test online
Thử test Ruby trên testdome thì free online coding test chỉ show ra có 2 bài. Thử làm và kết quả là như này :)
Ruby TEST
Chuẩn bị cho bài test đầu vào RoR nên dịp này đang phải bận rộn với task self-study Ruby & Ruby on Rails.
Test Ruby: take free online test + self study + theo course
Test RoR: đọc trên guides của RoR + practice.
Ngoài ra có thể dùng AI để gen ra quiz thực hành :D
Đầu tư server riêng cả năm mà chưa kiếm được xèng :)
Dự định ban đầu, là mua một con VM giá rẻ đủ dùng, để deploy phần mềm và chạy mấy EA, nhưng chưa kiếm được xèng nào :D
Mục tiêu 1: deploy phần mềm - OK, phần mềm demo vẫn chạy, nhưng khách hàng chưa chốt dùng, nên dừng ở công đoạn demo
Mục tiêu 2: tạm dừng EA vì hết xèng tiêu (rút ra tiêu nhưng ko có xèng nạp lại) - cái khó của nhà nghèo!