Posts

#25 Ruby on Rails application performance and security tools

Security -  rack-attack gem Brakeman gem Performance tools -   bullet rails_best_practice  rubycritic,  rubocop  rack-mini-profiler  spring, memory_profiler  Appsignal(paid) New Relic(paid)  Bullet gem(N+1 query)  rails_best_practice  rubycritic   rubocop brakeman  rack-mini-profiler  spring memory_prof

#24 Some useful gems list

  Purpose gem Debugging Pry Email test Letter Opener Testing rspec simplecov(check test code coverage) Factory_bot rswag faker environment variables figaro/magic-multiconnection tracking visits ahoy Background job sidekiq Search elasticseacrh deployment capistrano-rails Database pg cache redis serialize json data active_model_serializers login devise scheduler(cron job) rufus-scheduler notify exception via email exception_notification push notification ruby-push-notifications Json Web Token (JWT)  for token based authentication RabbitMQ bunny Security https://github.com/Snorby/snorby puma_worker_killer spring magic_multi_connection allocation_stats puma_worker_killer hyper-rails memory_profiler

#23. RoR commands

Remove  master.key and credentials.yml.enc then run following command to regenerate it, EDITOR="vim --wait" rails credentials:edit cat /etc/apt/sources.list.d/pgadmin4.list If you have UFW firewall configured, allow http and https traffic. sudo ufw allow http sudo ufw allow https For taking dump, psql -U your_user_name -h your_remote_ip -p 5432 -d your_db_name -f Path_for_db_dump_file bundle exec rake jobs:work Start queue, RAILS_ENV=development bin/delayed_job --queues=queue_name1,queue_name2,queue_name3 start​​ Stop queue, RAILS_ENV=development bin/delayed_job --queues=queue_name1,queue_name2,queue_name3 stop rvm gemset create your_gemset_name which rvm gemset location /home/{​​​​​​​​{​​​​​​​​user}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​/.rvm/gems like,  /home/raj/.rvm/gems rvm gemset list rvm use ruby-3.0.0@your_gemset_name rvm -- rvmrc ruby-3.0.0@your_gemset_name Editor I used - Rubymine/Sublime/VisualCode rvm gemdir gem li...

#22. Getting started with an existing Rails project

Start with following, routes  rake routes readme schema *_id search - for association project structure models lib/* controllers views rails test cases Use rails debuggers tool like pry Use browser dev tools see the flow with logs

#21. Rails scope

Author has_many books books belongs_to author Named Scope scope :available, -> { where(available: true) } select 'books'.* from books where books.available = 't' scope :unavailable, -> { where(available: [nil, false]) } select 'books'.* from books where books.available = 'f' or books.available is null scope :public_status, -> { where(status:  'public') } 3.1.2 :004 > Article.public_status   Article Load (0.2ms)  SELECT "articles".* FROM "articles" WHERE "articles"."status" = ? AND "articles"."status" = ?  [["status", "public"], ["status", "public"]] Here two times same status(‘public’) checked because one of the default scope and one of the named scope( public_status ). Author.joins(:books).merge(Book.available) select authors.* from authors inner join books on books.author_id=authors.id where books.available = 't' We can achi...

#20. List of things a RoR developer should be aware about

Environment variables Ruby Version Manager - RVM, rbenv gemset, bundler Rails App Structure rackup file - config.ru params - paraqmeters in rails query parameters Why http://localhost:3000/users/1 and not http://localhost:3000/users?id=1 Restful API Agile methodlologies MVC design patterns Why just instance variables pass from controller to view active record rails scope - named, default, unscope

#19. MySQL date time related query

 select CONVERT_TZ(now(), '+00:00', '+05:30') as converted_datetime; # converted_datetime '2022-07-06 19:28:31' select now() as current_dt; # current_dt '2022-07-06 13:56:07' select CURDATE() as current_dt; # current_dt '2022-07-06' SELECT @@global.time_zone, @@session.time_zone; # @@global.time_zone, @@session.time_zone 'SYSTEM', 'SYSTEM' select timediff(now(),convert_tz(now(),@@session.time_zone,'+00:00')); # timediff(now(),convert_tz(now(),@@session.time_zone,'+00:00')) '10:00:00' select convert_tz(now(),@@session.time_zone,'+00:00'); # convert_tz(now(),@@session.time_zone,'+00:00') '2022-07-06 04:03:47' select @@session.time_zone; # @@session.time_zone 'SYSTEM' SELECT @@system_time_zone; # @@system_time_zone 'AEST' SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP); # TIMEDIFF(NOW(), UTC_TIMESTAMP) '10:00:00' select UTC_TIMESTAMP; # UTC_TIMESTAMP '2022-07-06 04:07:...

#18. Ruby on Rails usefull commands

 gem install rails rails new hrms -d postgresql

#17. RVM useful commands

 rvm get head - update rvm rvm install ruby - install latest version of ruby rvm list known - list all known version of Ruby rvm list  - list all installed version of ruby rvm install ruby-3.2  - install ruby version 3.2 rvm --default use ruby-3.2.0-preview1 - set default version for ruby

#16. postgresql useful commands

Remove commands sudo apt-get --purge remove postgresql postgresql-* dpkg -l | grep postgres - list all postgres related packages sudo rm -rf /var/lib/postgresql/ sudo rm -rf /var/log/postgresql/ sudo rm -rf /etc/postgresql/ sudo deluser postgres sudo apt-get --purge remove postgresql postgresql-doc postgresql-common pg_config --version  psql --version  Install commands sudo apt update && sudo apt upgrade sudo apt install postgresql postgresql-contrib sudo systemctl start postgresql.service Postgres uses a concept called “roles” to handle authentication and authorization. sudo -i -u postgres - switch over to postgres account psql - access postgresql prompt \q - exit from postgresql prompt sudo -u postgres psql - open postgres prompt without switching accounts create new role sudo -i -u postgres createuser --interactive or with sudo command, sudo -u postgres createuser --interactive reset password of the role sudo -u postgres psql alter role aarya with password 'Pass@t...

# 15. My used gems list

-------- For RSpec testing ------------ gem 'capybara' gem 'selenium-webdriver' gem 'webdrivers' gem 'rails-controller-testing' gem 'faker' gem 'factory_bot_rails' gem 'rspec-rails' gem 'rswag' - testing and API documentation ------- for code quality --------- gem 'rubocop' -----------------Miscellaneous-------------- gem 'mini_racer' - for java script runtime gem 'caxlsx' - for excel sheet gem 'caxlsx_rails' gem 'active_link_to' gem 'simple_calendar' - for calendar gem 'jquery-ui-rails' gem 'jquery-rails' gem 'bootstrap' gem 'awesome_print' --------- database --------- gem 'mysql2' gem 'sqlite3' ---------------------------------- gem 'faraday' - For API calling  gem 'oj' -  For JSON parser gem 'paho-mqtt' - for interacting with the mqtt server gem 'dalli' - for memcache

#14. Rails notes command

 raj@linux:~/workspace/test_app$ rails notes -h Usage:   rails notes [options] Options:   -a, [--annotations=one two three]  # Filter by specific annotations, e.g. Foobar TODO Example, raj@linux:~/workspace/test_app$ rails notes -a DEBUG app/controllers/configs_controller.rb:   * [6] This is not exactly working raj@linux:~/workspace/test_app$ rails notes -a DEBUG TEST TODO app/controllers/application_controller.rb:   * [5] [TODO] Check this method for optimization app/controllers/configs_controller.rb:   * [6] [DEBUG] This is not exactly working app/controllers/feedbacks_controller.rb:   * [2] [TEST] Have to write test cases for this method raj@linux:~/workspace/test_app$ rails notes app/controllers/application_controller.rb:   * [5] [TODO] Check this method for optimization

#12. Memcache

Uninstallation/Installation, sudo apt-get remove memcached sudo apt-get remove --auto-remove memcached sudo apt update && sudo apt upgrade sudo apt install memcached  # For the use of mem-cache gem 'dalli' root@test_app:~# memcached -h | head -1 memcached 1.5.22 rails dev:cache root@test_app:~# ls tmp/ cache  data  development_secret.txt  miniprofiler  pids  res  restart.txt  sockets root@test_app:~# rails dev:cache Development mode is now being cached. root@test_app:~# ls tmp/ cache  caching-dev.txt data  development_secret.txt  miniprofiler  pids  res  restart.txt  sockets root@test_app:~# rails dev:cache Development mode is no longer being cached. root@test_app:~# ls tmp/ cache  data  development_secret.txt  miniprofiler  pids  res  restart.txt  sockets touch tmp/restart.txt root@test_app:~# ls tmp/ cache  caching-dev.txt data  development_secret.txt ...

#10. positive? method

 3.0.4 :001 > 0.positive?  => false  3.0.4 :002 > 1.positive?  => true  3.0.4 :003 > -1.positive?  => false

#8. nginx+puma deployment using capistrano

 In the Gemfile, ---------------------------------------- group :development do   gem 'capistrano',         require: false   gem 'capistrano-rvm',     require: false   gem 'capistrano-rails',   require: false   gem 'capistrano-bundler', require: false   gem 'capistrano3-puma',   require: false end -------------------------------------------------- bundle install cap install create a file as,  /home/raj/workspace/chat/config/nginx.conf ------------------------------------------------ upstream puma {   server unix:///home/raj/deployed_apps/chat/shared/tmp/sockets/chat-puma.sock; } server {   listen 80 default_server deferred;   # server_name example.com;   root /home/raj/deployed_apps/chat/current/public;   access_log /home/raj/deployed_apps/chat/current/log/nginx.access.log;   error_log /home/raj/deployed_apps/chat/current/log/nginx.error.log info;   location ...

#11. Run rails app in production mode

Check in produciton.rb, it should be false, config.assets.compile = false  precompile the assets, RAILS_ENV=production bundle exec rake assets:precompile It should be set in the env file as true config.public_file_server.enabled = true Then run server as, rails s -e production or RAILS_ENV=production rails s

#13. docker helpful commands

Restarting docker -   service docker restart docker images -a docker rmi Image Image

#6. Fetch time in rails

 In the Rails do not prefer to use Time.now, Date.today etc We should always prefer to use it with zone like, Time.zone.now, Time.zone.today etc. but why so? Beacause when we fetch Time.now its always return system local time and ignore  config.time_zone  set in the  application.rb. file. Here is the example tested in the rails console, 3.0.3 :001 > Time.now  => 2022-04-19 09:57:58.413034249 +0530  3.0.3 :002 > Time.zone  => #<ActiveSupport::TimeZone:0x000055704feec360 @name="UTC", @tzinfo=#<TZInfo::DataTimezone: Etc/UTC>, @utc_offset=nil>  3.0.3 :003 > Time.zone.now  => Tue, 19 Apr 2022 04:28:07.277000358 UTC +00:00  3.0.3 :004 > Time.zone = 'Sydney'  => "Sydney"  3.0.3 :005 > Time.zone  => #<ActiveSupport::TimeZone:0x000055705192d850 @name="Sydney", @tzinfo=#<TZInfo::DataTimezone: Australia/Sydney>, @utc_offset=nil>  3.0.3 :008 > Time.now  => 2022...

#7. Setting environment variables for rails app in ubuntu

Never keep any secret data in public folder. Always use environment variables to keep secret data. Suppose we want to set postgresql username and password as environment variables  in Ubuntu then do as, # type the following in the terminal to write in the .bashrc file. echo 'export MY_POSTGRESQL_USERNAME="rajkumar"' >> ~/.bashrc echo 'export MY_POSTGRESQL_PASSWORD="HJH34df@dff#@"' >> ~/.bashrc reload .bashrc as, source ~/.bashrc In order to print environment variables prepend it with $ as,  echo $MY_POSTGRESQL_USERNAME echo $MY_POSTGRESQL_PASSWORD test environment variables as, echo $MY_POSTGRESQL_USERNAME rajkumar echo $MY_POSTGRESQL_PASSWORD HJH34df@dff#@ Also use ubuntu command printenv to print all the environment variables. then in the database.yml use these environment variables as, development:   adapter: postgresql   encoding: unicode   host: localhost   username: <%= ENV["MY_POSTGRESQL_USERNAME"] %>   password: ...

#9. Some useful heroku commands

Heroku commands sudo snap install --classic heroku heroku login heroku create git config --list --local | grep heroku git push heroku main heroku run rake db:migrate heroku apps:rename kamb2017 heroku ps:scale web=1 heroku ps heroku open heroku logs heroku logs --tail heroku run rails console heroku config - view  heroku config:set MY_PASS=secret - set heroku config:get MY_PASS - view heroku config:unset MY_PASS - remove heroku config -a rk-rails-app - list all environment variables heroku apps - list all the heroku apps  heroku config -a rk-rails-app --json - list all environment variables in json format heroku run -a rk-rails-app printenv - print environment variables