Skip to content

Instantly share code, notes, and snippets.

@yshmarov
Last active April 16, 2024 07:29
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save yshmarov/758a04798c3400cf125de27659dab43e to your computer and use it in GitHub Desktop.
Save yshmarov/758a04798c3400cf125de27659dab43e to your computer and use it in GitHub Desktop.
Ruby on Rails 6: Learn 25+ gems and build a Startup MVP 2020
# All AWS C9 envments
https://eu-central-1.console.aws.amazon.com/cloud9/home?region=us-east-1
# Instance management
https://console.aws.amazon.com/ec2/home?region=eu-central-1#Instances:sort=instanceId
# Create AWS C9 environment
https://eu-central-1.console.aws.amazon.com/cloud9/home/create
Setting - set tabs to 2
Ctrl+E to search file
Alt+T - new terminal
Alt+W - close current tab
Ctrl+] - next tab
Ctrl+[ - prev tab
Ctrl+D - delete current line of code
Increase AWS storage size
https://docs.aws.amazon.com/cloud9/latest/user-guide/move-environment.html#move-environment-resize
//clean webpacker
bin/rails webpacker:clean
bin/rails tmp:clear
bin/rails log:clear
# install latest version of Ruby, Rails, Postgresql, Yarn, Webpacker
rails -v
ruby -v
rvm list
rvm install ruby-2.7.2
rvm --default use 2.7.2
rvm uninstall 2.7.1
rvm uninstall 2.7.0
rvm uninstall 2.6.3
rvm uninstall 2.6.5
gem install rails -v 6.0.3.4
gem update rails
gem update --system
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt update
sudo apt install postgresql libpq-dev redis-server redis-tools yarn
ruby -v
rails -v
pg_config --version
# create rails app
rails new myappname --database=postgresql
cd myappname
bundle
yarn
# postgresql setup
sudo su postgres
createuser --interactive
ubuntu
y
exit
# to make the server work, add the url to development.rb
config.hosts << "2b8c1faf3a934c25b7e01d446161bfff.vfs.cloud9.us-east-1.amazonaws.com"
# start server
rails db:create
rails db:migrate
rails s
#Ruby on Rails
rvm install ruby-2.7.1
rvm --default use 2.7.1
rvm uninstall 2.6.5
rvm uninstall 2.6.6
rvm uninstall 2.6.3
gem install rails -v 5.2.4.3
#Postgresql
sudo apt install postgresql libpq-dev
sudo su postgres
createuser --interactive
ubuntu
y
exit
http://github.com/
git config --global user.name "Yaro"
git config --global user.email yshmarov@gmail.com
git init
git status
git add -A
git commit -m 'initialize app'
# https://github.com/new
git remote add origin https://github.com/yshmarov/rubygems.git
git push -u origin master
// delete last commit from github
git reset HEAD^ --hard
git push -f
// git uncheck last commit
git reset --soft HEAD~1
// git reset to specific commit
git reset --hard c14809fa
// forward-moving undo last commit
git revert HEAD
git add -A
git commit -m 'undo last commit'
// forward-moving undo commit-before-last-commit
git revert HEAD~1
git add -A
git commit -m 'undo commit-before-last-commit'
//check to which repo you are connected
git remote -v
//set remote repo
git remote set-url origin https://github.com/yshmarov/edurge.git
Git branches:
//Create branch
git checkout -b "i18n"
//Show all branches:
git branch
//Switch to master
git checkout master
//Merge "i18n" with master
git merge i18n
//Delete "i18n" branch
git branch -D i18n
//pull remote branch
git fetch origin stripe2
git checkout -b stripe2 origin/stripe2
http://heroku.com/
# creating the first page
rails g controller home index
# Add the following line to routes.rb
root 'home#index'
git add -A
git commit -m 'add home index controller'
# installing heroku
npm uninstall -g heroku-cli
sudo snap install heroku --classic
npm install -g heroku
heroku create
heroku buildpacks:add heroku/ruby
git remote -v
git push heroku master
heroku run rake db:migrate
# if you want to connect to an existing heroku app
heroku git:remote -a yourappnamegoeshere
# see logs
heroku logs --tail
# to run console activerecord commands
heroku run rails c
# restart
heroku restart
# log into heroku from console
heroku login -i
# clone app from heroku to local
heroku git:clone -a bobablack
https://edgeguides.rubyonrails.org/action_text_overview.html
// Console
rails action_text:install
// application.js
require("trix")
require("@rails/actiontext")
// actiontext.scss
@import "trix/dist/trix";
// application.scss
@import "./actiontext.scss";
// app/models/course.rb
class Course < ApplicationRecord
has_rich_text :description
end
// app/views/courses/_form.html.erb
<%= f.label :description %>
<%= f.rich_text_area :description %>
// application.html.haml
= render 'layouts/messages'
// _messages.html.haml
- flash.each do |name, msg|
- if msg.is_a?(String)
%div{:class => "alert alert-#{name.to_s == 'notice' ? 'success' : 'danger'}", :role => "alert"}
%button.close{"aria-hidden" => "true", "data-dismiss" => "alert", :type => "button"} ×
= content_tag :div, msg, :id => "flash_#{name}"
// courses_controller.rb
def index
if params[:title]
@courses = Course.where('title ILIKE ?', "%#{params[:title]}%") #case-insensitive
else
@courses = Course.all
end
end
// _header.html.haml
.form-inline.my-2.my-lg-0
= form_tag(courses_path, method: :get) do
.input-group
= text_field_tag :title, params[:title], autocomplete: 'off', placeholder: "Find a course", class: 'form-control-sm'
%span.input-group-append
%button.btn.btn-primary.btn-sm{:type => "submit"}
%span.fa.fa-search{"aria-hidden" => "true"}
CREATE CREDENTIALS & EDIT
rails credentials:edit
EDITOR=vim rails credentials:edit
WORKING WITH VIM
For inserting
Press i //Do required editing
For exiting
Press Esc
:wq //for exiting and saving
:q! //for exiting without saving
FIND A CREDENTIAL
rails c
Rails.application.credentials.dig(:aws, :access_key_id)
or if an env variable is used
Rails.application.credentials[Rails.env.to_sym][:aws][:access_key_id]
In production:
heroku config:set RAILS_MASTER_KEY=123456789
or
heroku config:set RAILS_MASTER_KEY=`cat config/master.key`
// courses_controller.rb
def index
if params[:name]
@courses = Course.published.approved.where('name ILIKE ?', "%#{params[:name]}%") #case-insensitive
#@courses = Course.where('name LIKE ?', "%#{params[:name]}%") #case-sensitive
#@courses = Course.where('LOWER(name) LIKE LOWER(?)', "%#{params[:name]}%") #make lowercase
else
@courses = Course.published.approved.all
end
end
// in any view:
.form-inline.my-2.my-lg-0
= form_tag(posts_path, method: :get) do
.input-group
= text_field_tag :name, params[:name], autocomplete: 'off', placeholder: "Find a post", class: 'form-control-sm'
%span.input-group-append
%button.btn.btn-primary.btn-sm{:type => "submit"}
%span.fa.fa-search{"aria-hidden" => "true"}
//inline elsif
vote_text = current_user&.voted_for?(@post) ? "No" : "Yes"
// gemfile:
gem 'wicked_pdf' #PDF for Ruby on Rails
gem 'wkhtmltopdf-binary', group: :development
gem 'wkhtmltopdf-heroku', group: :production
config/wicked_pdf.rb
WickedPdf.config ||= {}
WickedPdf.config.merge!({
#YOUR CONFIG HERE
})
@yshmarov
Copy link
Author

  InstaAccessToken.where(expires_at: ..14.days.from_now)
  InstaAccessToken.where(expires_at: 1.week.ago..Float::INFINITY)

@yshmarov
Copy link
Author

yshmarov commented Dec 1, 2022

@favorited_teams_by_school = @user.favorited_teams.group_by { |team| team.school_id }
@favorited_teams_by_school = @user.favorited_teams.group_by(&:school_id)

@yshmarov
Copy link
Author

redirect_to "https://insta2blog.com", allow_other_host: true

@yshmarov
Copy link
Author

yshmarov commented Jan 3, 2023

test broadcast with minitest
https://apidock.com/rails/v6.0.0/ActionCable/TestHelper/assert_broadcast_on

test "notifications are sent to same group" do
    stream = @group
    target = "icon"

    assert_broadcast_on stream, turbo_stream_action_tag("replace", target: target, template: %(<span class='icon'>notification_new</span>)) do
      Post.create(title: 'A new post')
    end
end

@yshmarov
Copy link
Author

yshmarov commented Jan 9, 2023

User.in_order_of(:status, %w(working sleeping vacation))

@yshmarov
Copy link
Author

rm -rf myapp/
tag git@github.com:myorg/myapp.git

@yshmarov
Copy link
Author

# remote GH gem path
  gem "mygem", github: "yshmarov/mygem", branch: "main"
# local gem path
  gem "mygem", path: "/Users/yaroslavshmarov/Documents/GitHub.nosync/mygem"

@yshmarov
Copy link
Author

ActionCable.server.pubsub.redis_connection_for_subscriptions.sadd 'online_users', current_user.id
ActionCable.server.pubsub.redis_connection_for_subscriptions.srem 'online_users', current_user.id
user_ids = ActionCable.server.pubsub.redis_connection_for_subscriptions.smembers('online_users')

@yshmarov
Copy link
Author

yshmarov commented Mar 1, 2023

https://github.com/gbuesing/rack-host-redirect

    config.middleware.use Rack::HostRedirect, {
      "app.com" => "www.app.com",
      "app.herokuapp.com" => "www.app.com",
      "www.app.test" => "app.test",
    }

@yshmarov
Copy link
Author

cat ~/.ssh/id_ed25519.pub | pbcopy

@yshmarov
Copy link
Author

EDITOR="rubymine --wait" rails credentials:edit --environment=development

@yshmarov
Copy link
Author

    <%= form.submit "Save organization", class: "btn-primary disabled:opacity-75", onclick: "this.disabled=true;this.value='Sending, please wait...';this.form.requestSubmit();" %>

@yshmarov
Copy link
Author

yshmarov commented Apr 3, 2023

chatgpt useful for:

  • write a test for this code
  • rewrite minitest to rspec
  • how can I write this code better?

@yshmarov
Copy link
Author

ps aux | grep ruby
kill -9 8247

@yshmarov
Copy link
Author

yshmarov commented May 3, 2023

"describe" and "it" with minitest

  describe "foo" do
    it "bar" do
      assert User.admin?
    end
  end

@yshmarov
Copy link
Author

    @talks = Talk.order("RANDOM()").excluding(@talk).limit(6)

@yshmarov
Copy link
Author

<%= form.date_select(:valid_from, { order: [:day, :month, :year], use_month_numbers: true, prompt: { day: 'Day', month: 'Month', year: 'Year' }, }) %>

@yshmarov
Copy link
Author

yshmarov commented Jul 1, 2023

Turbo native notes:
absolute minimum amount of native code to write? strada = remove js boilerplate? what is a turbo native app?

turbo native lets you publish a rails app to app store

has to add native functionality (push notifications!)

native maps
SSO

https://github.com/joemasilotti/TurboNavigator
https://github.com/hotwired/turbo-ios
https://www.hackingwithswift.com/100
https://masilotti.com/swift-for-ruby-developers/

@yshmarov
Copy link
Author

yshmarov commented Jul 5, 2023

Rake tasks 101

heroku run rake import_my_stuff

# lib/tasks/import_data.rake

desc "adds activities data"
task import_my_stuff: :environment do
  require "csv"
  filename = Rails.root.join("data", "activities.csv")
  CSV.foreach(filename, headers: true) do |row|
    activity = Activity.find_by(name: row["name"])
      activity.update_attributes(row.to_hash)
end

@yshmarov
Copy link
Author

rails assets:clobber

@yshmarov
Copy link
Author

yshmarov commented Nov 9, 2023

gem 'passwordless', github: 'mikker/passwordless', branch: 'master'
# inspect code from passwordless gem command:
# bundle open passwordless
# To open a bundled gem, set $EDITOR or $BUNDLER_EDITOR
# export EDITOR="code --wait"
# clear cached gems:
# bundle clean --force

@yshmarov
Copy link
Author

yshmarov commented Nov 9, 2023

gem "mygem", path: "/Users/yaroslavshmarov/Documents/GitHub.nosync/mygem"

@yshmarov
Copy link
Author

onclick: "this.disabled=true;this.value='Sending, please wait...';this.form.requestSubmit();"

@yshmarov
Copy link
Author

  root to: redirect("/orders")
  get "settings", to: redirect("/settings/filter")
  get "settings", to: redirect { |params, request|
    "/settings/filter?#{request.query_string}"
  }

@yshmarov
Copy link
Author

yshmarov commented Dec 6, 2023

rails new askvote -a=propshaft -d=postgresql -c=tailwind --main
rails new askvote -a=propshaft -c=tailwind --main

@yshmarov
Copy link
Author

yshmarov commented Feb 2, 2024

kill -9 $(ps -x | grep "Google Chrome" | awk "{print $1}")

@yshmarov
Copy link
Author

yshmarov commented Feb 2, 2024

Asset compilation

Normally we use bin/dev to run the server and dynamically compile assets.

If for some reason you ran rails assets:precompile, they will no longer compile dynamically (only when you restart).

Run rails assets:clobber to return asset compilation back to normal.

@yshmarov
Copy link
Author

  config.i18n.raise_on_missing_translations = true
  config.action_view.annotate_rendered_view_with_filenames = true

@yshmarov
Copy link
Author

yshmarov commented Mar 3, 2024

create rails app on main branch rails new weblog --main

rails new askvote --main -d=postgresql -c=tailwind -a=propshaft

@yshmarov
Copy link
Author

include Rails.application.routes.url_helpers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment