lundi 30 août 2021

exercise on how a bank works with the ruby language [closed]

Bank

You must create a bank.

This bank must have customers

A customer must have an account

An account must have a balance

Customers must be able to transfer their balance to each other

Display an error message if the transfer is impossible

Display a success message if the transfer is successful

Scenario

Create a bank and two accounts in this bank

Create a customer A,B,C and D

Assign accounts to customers with balances of 0

Customer A makes a deposit of 100000

Customer B has a deposit of 25000

Customer C has a deposit of 30000

Customer D makes a deposit of 400000

Customer B makes a transfer of 50,000 to customer A

Customer A makes a transfer of 70000 to customer B

Display the balance of customer A

Display the balance of customer B

Display the total balance of the bank

Display the bank's customers with a balance higher than 100000

The bank takes 5% interest on all accounts

Display the balance of interest collected by the bank

The bank can give credits below 300000 to customers with a balance below 50000

Customer D tries to get a credit of 200000

Customer A is trying to get a credit of 400000

Customer C tries to get a credit of 150,000

Customer B makes a transfer of 100000 to customer D

Display the balance of all customers

Display the sum of all the credits granted to the customers

do you have an idea of how to proceed

How can I install yarn on the docker environment?

Now, I am trying to create the environment for Ruby on rails on docker. I read the documents and some blogs some people wrote and tried. But I got errors and couldn't go through with it.

It seems like that I have to install yarn in the docker environment but I don't know if I did it in a right way or not.

If anyone knows anything, please tell me.

what I wrote so far is something like this.

Dockerfile

FROM ruby:3.0.2
RUN apt-get update -qq && apt-get install -y nodejs postgresql-client


RUN mkdir /docker-test2
WORKDIR /docker-test2
COPY Gemfile /docker-test2/Gemfile
COPY Gemfile.lock /docker-test2/Gemfile.lock
RUN bundle install
COPY . /docker-test2


# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Start the main process.
CMD ["rails", "server", "-b", "0.0.0.0"]

docker-compose.yml

version: "3.9"
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/docker-test2
    ports:
      - "3000:3000"
    depends_on:
      - db

entrypoint.sh

#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /docker-test2/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"

when I tried docker-compose run the error says something like this.

    Attaching to docker-test2_db_1, docker-test2_web_1
db_1   | The files belonging to this database system will be owned by user "postgres".
db_1   | This user must also own the server process.
db_1   | 
db_1   | The database cluster will be initialized with locale "en_US.utf8".
db_1   | The default database encoding has accordingly been set to "UTF8".
db_1   | The default text search configuration will be set to "english".
db_1   | 
db_1   | Data page checksums are disabled.
db_1   | 
db_1   | fixing permissions on existing directory /var/lib/postgresql/data ... ok
db_1   | creating subdirectories ... ok
db_1   | selecting dynamic shared memory implementation ... posix
db_1   | selecting default max_connections ... 100
db_1   | selecting default shared_buffers ... 128MB
db_1   | selecting default time zone ... Etc/UTC
db_1   | creating configuration files ... ok
db_1   | running bootstrap script ... ok
db_1   | performing post-bootstrap initialization ... ok
db_1   | syncing data to disk ... ok
db_1   | 
db_1   | 
db_1   | Success. You can now start the database server using:
db_1   | initdb: warning: enabling "trust" authentication for local connections
db_1   | You can change this by editing pg_hba.conf or using the option -A, or
db_1   | --auth-local and --auth-host, the next time you run initdb.
db_1   | 
db_1   |     pg_ctl -D /var/lib/postgresql/data -l logfile start
db_1   | 
db_1   | waiting for server to start....2021-08-30 09:03:01.284 UTC [47] LOG:  starting PostgreSQL 13.4 (Debian 13.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1   | 2021-08-30 09:03:01.285 UTC [47] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1   | 2021-08-30 09:03:01.299 UTC [48] LOG:  database system was shut down at 2021-08-30 09:02:59 UTC
db_1   | 2021-08-30 09:03:01.322 UTC [47] LOG:  database system is ready to accept connections
db_1   |  done
db_1   | server started
db_1   | 
db_1   | /usr/local/bin/docker-entrypoint.sh: ignoring /docker-entrypoint-initdb.d/*
db_1   | 
db_1   | 2021-08-30 09:03:01.497 UTC [47] LOG:  received fast shutdown request
db_1   | waiting for server to shut down....2021-08-30 09:03:01.498 UTC [47] LOG:  aborting any active transactions
db_1   | 2021-08-30 09:03:01.500 UTC [47] LOG:  background worker "logical replication launcher" (PID 54) exited with exit code 1
db_1   | 2021-08-30 09:03:01.500 UTC [49] LOG:  shutting down
db_1   | 2021-08-30 09:03:01.544 UTC [47] LOG:  database system is shut down
db_1   |  done
db_1   | server stopped
db_1   | 
db_1   | PostgreSQL init process complete; ready for start up.
db_1   | 
db_1   | 2021-08-30 09:03:01.627 UTC [1] LOG:  starting PostgreSQL 13.4 (Debian 13.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1   | 2021-08-30 09:03:01.627 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1   | 2021-08-30 09:03:01.627 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1   | 2021-08-30 09:03:01.631 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1   | 2021-08-30 09:03:01.652 UTC [66] LOG:  database system was shut down at 2021-08-30 09:03:01 UTC
db_1   | 2021-08-30 09:03:01.671 UTC [1] LOG:  database system is ready to accept connections
db_1   | 
db_1   | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1   | 
db_1   | 2021-08-30 09:04:33.607 UTC [1] LOG:  starting PostgreSQL 13.4 (Debian 13.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1   | 2021-08-30 09:04:33.607 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1   | 2021-08-30 09:04:33.607 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1   | 2021-08-30 09:04:33.611 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1   | 2021-08-30 09:04:33.659 UTC [27] LOG:  database system was interrupted; last known up at 2021-08-30 09:03:01 UTC
db_1   | 2021-08-30 09:04:34.659 UTC [27] LOG:  database system was not properly shut down; automatic recovery in progress
db_1   | 2021-08-30 09:04:34.676 UTC [27] LOG:  redo starts at 0/15C6DD8
db_1   | 2021-08-30 09:04:34.676 UTC [27] LOG:  invalid record length at 0/15C6E10: wanted 24, got 0
db_1   | 2021-08-30 09:04:34.676 UTC [27] LOG:  redo done at 0/15C6DD8
db_1   | 2021-08-30 09:04:34.694 UTC [1] LOG:  database system is ready to accept connections
db_1   | 
db_1   | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1   | 
db_1   | 2021-08-30 09:11:48.053 UTC [1] LOG:  starting PostgreSQL 13.4 (Debian 13.4-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
db_1   | 2021-08-30 09:11:48.053 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1   | 2021-08-30 09:11:48.053 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1   | 2021-08-30 09:11:48.056 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1   | 2021-08-30 09:11:48.105 UTC [27] LOG:  database system was interrupted; last known up at 2021-08-30 09:04:34 UTC
db_1   | 2021-08-30 09:11:49.433 UTC [27] LOG:  database system was not properly shut down; automatic recovery in progress
db_1   | 2021-08-30 09:11:49.436 UTC [27] LOG:  redo starts at 0/15C6E88
db_1   | 2021-08-30 09:11:49.436 UTC [27] LOG:  invalid record length at 0/15C6EC0: wanted 24, got 0
db_1   | 2021-08-30 09:11:49.436 UTC [27] LOG:  redo done at 0/15C6E88
db_1   | 2021-08-30 09:11:49.454 UTC [1] LOG:  database system is ready to accept connections
web_1  | => Booting Puma
web_1  | => Rails 6.1.4.1 application starting in development 
web_1  | => Run `bin/rails server --help` for more startup options
web_1  | Exiting
web_1  | /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:103:in `rescue in load': Webpacker configuration file not found /docker-test2/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /docker-test2/config/webpacker.yml (RuntimeError)
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:95:in `load'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:92:in `data'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:88:in `fetch'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:43:in `public_path'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:47:in `public_output_path'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:51:in `public_manifest_path'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/manifest.rb:83:in `load'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/manifest.rb:18:in `refresh'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/commands.rb:47:in `bootstrap'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker.rb:35:in `bootstrap'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/railtie.rb:41:in `block in <class:Engine>'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/initializable.rb:32:in `instance_exec'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/initializable.rb:32:in `run'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/initializable.rb:61:in `block in run_initializers'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:228:in `block in tsort_each'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:431:in `each_strongly_connected_component_from'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:349:in `block in each_strongly_connected_component'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:347:in `each'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:347:in `call'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:347:in `each_strongly_connected_component'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:226:in `tsort_each'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:205:in `tsort_each'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/initializable.rb:60:in `run_initializers'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/application.rb:391:in `initialize!'
web_1  |        from /docker-test2/config/environment.rb:5:in `<main>'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
web_1  |        from /usr/local/bundle/gems/zeitwerk-2.4.2/lib/zeitwerk/kernel.rb:34:in `require'
web_1  |        from /usr/local/bundle/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `block in require'
web_1  |        from /usr/local/bundle/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:299:in `load_dependency'
web_1  |        from /usr/local/bundle/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `require'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:54:in `require_relative'
web_1  |        from config.ru:3:in `block in <main>'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/builder.rb:116:in `eval'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/builder.rb:116:in `new_from_string'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/builder.rb:105:in `load_file'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/builder.rb:66:in `parse_file'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/server.rb:349:in `build_app_and_options_from_config'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/server.rb:249:in `app'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/server.rb:422:in `wrapped_app'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:77:in `log_to_stdout'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:37:in `start'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:144:in `block in perform'
web_1  |        from <internal:kernel>:90:in `tap'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:135:in `perform'
web_1  |        from /usr/local/bundle/gems/thor-1.1.0/lib/thor/command.rb:27:in `run'
web_1  |        from /usr/local/bundle/gems/thor-1.1.0/lib/thor/invocation.rb:127:in `invoke_command'
web_1  |        from /usr/local/bundle/gems/thor-1.1.0/lib/thor.rb:392:in `dispatch'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/command/base.rb:69:in `perform'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/command.rb:48:in `invoke'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands.rb:18:in `<main>'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
web_1  |        from /docker-test2/bin/rails:5:in `<top (required)>'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `load'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `call'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/client/command.rb:7:in `call'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/client.rb:30:in `run'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/bin/spring:49:in `<top (required)>'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `load'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `<top (required)>'
web_1  |        from /docker-test2/bin/spring:10:in `require'
web_1  |        from /docker-test2/bin/spring:10:in `block in <top (required)>'
web_1  |        from <internal:kernel>:90:in `tap'
web_1  |        from /docker-test2/bin/spring:7:in `<top (required)>'
web_1  |        from bin/rails:2:in `load'
web_1  |        from bin/rails:2:in `<main>'
web_1  | /usr/local/lib/ruby/3.0.0/psych.rb:581:in `initialize': No such file or directory @ rb_sysopen - /docker-test2/config/webpacker.yml (Errno::ENOENT)
web_1  |        from /usr/local/lib/ruby/3.0.0/psych.rb:581:in `open'
web_1  |        from /usr/local/lib/ruby/3.0.0/psych.rb:581:in `load_file'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/compile_cache/yaml.rb:124:in `load_file'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:97:in `load'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:92:in `data'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:88:in `fetch'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:43:in `public_path'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:47:in `public_output_path'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/configuration.rb:51:in `public_manifest_path'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/manifest.rb:83:in `load'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/manifest.rb:18:in `refresh'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/commands.rb:47:in `bootstrap'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker.rb:35:in `bootstrap'
web_1  |        from /usr/local/bundle/gems/webpacker-5.4.2/lib/webpacker/railtie.rb:41:in `block in <class:Engine>'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/initializable.rb:32:in `instance_exec'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/initializable.rb:32:in `run'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/initializable.rb:61:in `block in run_initializers'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:228:in `block in tsort_each'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:431:in `each_strongly_connected_component_from'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:349:in `block in each_strongly_connected_component'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:347:in `each'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:347:in `call'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:347:in `each_strongly_connected_component'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:226:in `tsort_each'
web_1  |        from /usr/local/lib/ruby/3.0.0/tsort.rb:205:in `tsort_each'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/initializable.rb:60:in `run_initializers'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/application.rb:391:in `initialize!'
web_1  |        from /docker-test2/config/environment.rb:5:in `<main>'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
web_1  |        from /usr/local/bundle/gems/zeitwerk-2.4.2/lib/zeitwerk/kernel.rb:34:in `require'
web_1  |        from /usr/local/bundle/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `block in require'
web_1  |        from /usr/local/bundle/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:299:in `load_dependency'
web_1  |        from /usr/local/bundle/gems/activesupport-6.1.4.1/lib/active_support/dependencies.rb:332:in `require'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:54:in `require_relative'
web_1  |        from config.ru:3:in `block in <main>'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/builder.rb:116:in `eval'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/builder.rb:116:in `new_from_string'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/builder.rb:105:in `load_file'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/builder.rb:66:in `parse_file'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/server.rb:349:in `build_app_and_options_from_config'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/server.rb:249:in `app'
web_1  |        from /usr/local/bundle/gems/rack-2.2.3/lib/rack/server.rb:422:in `wrapped_app'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:77:in `log_to_stdout'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:37:in `start'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:144:in `block in perform'
web_1  |        from <internal:kernel>:90:in `tap'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands/server/server_command.rb:135:in `perform'
web_1  |        from /usr/local/bundle/gems/thor-1.1.0/lib/thor/command.rb:27:in `run'
web_1  |        from /usr/local/bundle/gems/thor-1.1.0/lib/thor/invocation.rb:127:in `invoke_command'
web_1  |        from /usr/local/bundle/gems/thor-1.1.0/lib/thor.rb:392:in `dispatch'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/command/base.rb:69:in `perform'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/command.rb:48:in `invoke'
web_1  |        from /usr/local/bundle/gems/railties-6.1.4.1/lib/rails/commands.rb:18:in `<main>'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
web_1  |        from /usr/local/bundle/gems/bootsnap-1.8.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
web_1  |        from /docker-test2/bin/rails:5:in `<top (required)>'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `load'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/client/rails.rb:28:in `call'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/client/command.rb:7:in `call'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/client.rb:30:in `run'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/bin/spring:49:in `<top (required)>'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `load'
web_1  |        from /usr/local/bundle/gems/spring-2.1.1/lib/spring/binstub.rb:11:in `<top (required)>'
web_1  |        from /docker-test2/bin/spring:10:in `require'
web_1  |        from /docker-test2/bin/spring:10:in `block in <top (required)>'
web_1  |        from <internal:kernel>:90:in `tap'
web_1  |        from /docker-test2/bin/spring:7:in `<top (required)>'
web_1  |        from bin/rails:2:in `load'
web_1  |        from bin/rails:2:in `<main>'
docker-test2_web_1 exited with code 1

I found someone saying that I have to install webpacker first so I tried something like this. docker-compose run web bundle exec rails webpacker:install and errors says

Yarn not installed. Please download and install Yarn from https://yarnpkg.com/lang/en/docs/install/ Exiting!

I thought I should install yarn in the image so I also tried docker run web sh and apt-get install yarn but nothing has changed.

I would really appreciate it if you help me.

Thank you.

samedi 28 août 2021

Refactor Rails controller

I am trying to achieve this feature:

Sent texts out to new authors.

It enables admin users to

  1. when authors published their first article in a specified timeframe, Compose and send out emails to authors

  2. Download a CSV file with a list of recipients.

I want to refactor the controller code in efficient way

 Models
class Email < ActiveRecord::Base
end

class User < ActiveRecord::Base
  has_many :articles
  scope :recent, -> { order("created_at DESC") }
end

class Article < ActiveRecord::Base
end




# Controller
class EmailsController < ApplicationController
  attr_accessor :email

  def new
    @email = Email.new
    if params[:date_from].present? && params[:date_to].present?
      fetch_users
    end
  end

  def create
    @email = Email.new(email_params)

    users = fetch_users
    recipients = []
    users.each do |user|
      recipients << user.email
    end

    if @email.save && send_mail_to_user(recipients)
      redirect_to emails_path, notice: "Emails Sent Successfully!"
    end
  end

  def download_csv
    users = fetch_users
    send_data to_csv(users), filename: "users-article-#{Time.zone.today}.csv"
  end

  private

    def to_csv(data)
      inputs = %w{id email name}
      CSV.generate(headers: true) do |csv|
        csv << attributes
        data.each do |user|
          csv << inputs.map { |attr| user.send(attr) }
        end
      end
    end

    def send_mail_to_user(users)
      users.each do |r|
        UserMailer.bulk_email(r).deliver_later
      end
    end

    def fetch_users
      @users = User.recent.joins(:articles).group("articles.user_id").where("`published_article_count` = 1").
        where("published_at Between ? AND ?", Date.parse(params[:date_from]), Date.parse(params[:date_to])).page(params[:page])
    end

    def email_params
      params.permit(:body, :date_from, :date_to)
    end
end

mercredi 25 août 2021

how to upload media file using fetch API and active storage to store media in rails?

I'm trying to store the image or video file in the database and along with image and video, i have some data to store.

I'm using fetch api to post the data and using ActiveStorage to store the image and video files. I have stored the text data to the database but unable to store the image and video files. Here below is the Section model

class Section < ApplicationRecord
    belongs_to :layout,dependent: :destroy
    has_many :media, through: :section_multimedia
    has_many :section_multimedia, dependent: :destroy
    has_one_attached :mediadata
    
end

Below is the show page along with javascript included

.border
    .row          
        .col-md-9
            .p-3
                button#imageModalButton.btn.btn-primary type="button" data-toggle="modal" data-target="#imageModal" <b>Design Layout</b>
                = link_to  "Preview", preview_layout_layout_path ,:class=>"btn btn-danger mx-3"
            
            / Here goes the overview of saved layout  
            . style="position:relative; background-color: #3C506F;height:500px; overflow:auto; "
 
            
                -@section.each do |sect|
                        
                    .border id="hello#{sect.id}"  style="position:absolute; height:#{sect.height}px; top:#{sect.position.split(",")[0]}px; left:#{sect.position.split(",")[1]}px;  width:#{sect.width}px;" #{sect.sectiontitle}
                end  
            
            
            
            



        .col-3.border-left
            .row
               .col-md-12
                  = text_field_tag 'search', nil, class: "form-control search col-11", placeholder: "Search.."
                  i.fa.fa-file-search
               = render 'layouts/gallery'


                


#imageModal.modal.fade aria-hidden="true"  aria-labelledby="exampleModalLabel" role="dialog"  tabindex="-1"
  .modal-dialog.modal-lg role="document"
    .modal-content style="width:800px"
        
            .row.bg-dark
                .col-md-4 
                    button.btn.btn-outline-primary#add-section Add Section
                .col-md-4 
                    button.btn.btn-outline-success#save-layout Save
                .col-md-4 
                    button.btn.btn-outline-danger  data-dismiss="modal" type="button"  Cancel
        
            .d-flex id="canvas" style="position:relative;background-color: black;height:500px; overflow:auto;"
                -if !@section.nil?
                    . style="position:relative; background-color: #3C506F;height:500px; overflow:auto; "
                 
            
                -@section.each do |sect|
                    = image_tag(sect.mediadata) if sect.mediadata.attached?
                        
                    .border id="sect#{sect.id}" class="custom"  style="position:absolute; height:#{sect.height}px; top:#{sect.position.split(",")[0]}px; left:#{sect.position.split(",")[1]}px;  width:#{sect.width}px;" #{sect.sectiontitle}

                   
                
                end  
                    
                


css:

    .section{
        height:250px;
        width :400px;
    }
    .custom:hover{
        background:#E4E5E6;

    }


javascript: 
        let canvas = document.getElementById('canvas')
        let addSectionBtn = document.getElementById('add-section')
        canvas.className= "row"
        canvas.setAttribute("height","100%")
    
        var position 
        var dimension
        var count =#{@section.count}+1
        

        addSectionBtn.addEventListener('click',(event)=>{

            let sectiondiv = document.createElement("div");
            let mediadiv = document.createElement("div");
            let input = document.createElement("input")
            let closebtn = document.createElement("button");
            let img = document.createElement("img");

            
            sectiondiv.setAttribute("id","section"+count);
            closebtn.className ='btn btn-outline-danger close'
            closebtn.setAttribute("value","close"+count);

            sectiondiv.className = "border absolute section ui-widget-content"

            
            mediadiv.appendChild(closebtn)
            sectiondiv.appendChild(mediadiv)
            


            

            mediadiv.setAttribute("id","media"+count)
            img.className = "absolute"
            img.setAttribute("id","image"+count);
            img.setAttribute("height","100%")
            img.setAttribute("width","100%")
            closebtn.setAttribute("id","close"+count)

            canvas.appendChild(sectiondiv)
            closebtn.innerHTML = '&times;';
            mediadiv.appendChild(input)
            input.setAttribute("class","file-input")
            input.setAttribute("name","mediadata")
            sectiondiv.appendChild(img);

            
            input.setAttribute("id","input"+count)
            input.setAttribute("type","file")
            input.setAttribute("accept","image/*,video/*")
            input.setAttribute("onchange","PreviewFile(this.id)")

            $("#section"+count).resizable();
            $("#section"+count).draggable();


            let sections = document.querySelectorAll(".section");

            for(var i=0;i<sections.length;i++){
                sections[i].addEventListener('click',(event)=>{
                    var id = event.target.id.split("section")[1]
                
                    
                })
            }

            // logic to remove the section from the layout 
            let closebtns = document.querySelectorAll('.close');
            for(var i=0;i<closebtns.length;i++){
                closebtns[i].addEventListener('click',(event)=>{
                    var id=event.target.id.split("close")[1]
                    $("#section"+id).remove()
                })

            }
          
        
            count++
            
        })

        function PreviewFile (id){
            var file = document.getElementById(id).files;
            if(file.length > 0){
                var fileReader = new FileReader();
                fileReader.onload = function(event){
                    
                    document.getElementById("image"+id.split("input")[1]).setAttribute("src",event.target.result)
                    $("#"+id).hide()
                    $("#closebtn"+id.split("input")[1]).hide()
                     
                }
                fileReader.readAsDataURL(file[0]);
            }           

        }
        
        

        let savebtn = document.getElementById('save-layout')
        
       
        // Saving layout sections  using jquery
        savebtn.addEventListener('click',(event)=>{

            // setting logic to get the updated position and dimension of each section 
            var position = []
            var dimension = []  
            let allSections =[]
            let filesId = []
            let layout_id = window.location.href.split("/layouts/")[1]

            let sections = document.querySelectorAll('.section')

            var inputElementArr = document.querySelectorAll('.file-input')

            var allimage = []
            sections.forEach((section)=>{
                
                var file = document.getElementById("input"+section.id.split("section")[1]).files
                
                position.push($("#"+section.id).position())
                dimension.push(($("#"+section.id).height())*$("#"+section.id).width())
                allSections.push(section.id)
                allimage.push(file[0])
                
                var temp = {sectionid:section.id,dimension: ($("#"+section.id).height())*$("#"+section.id).width(),position : $("#"+section.id).position() }
                if (file){
                   temp.file = file[0]

                }
                allimage.push(temp)
            })
        
           
            storeData(allSections,position,dimension,allimage,layout_id);

            

            
        })

        function storeData(allSections ,position ,dimension,allimage,layout_id){
                
            let data =[]
            // setting section data in data variable as objects 
            for(var i=0; i < allSections.length; i++){
                var height = $("#"+allSections[i]).height()
                var width = $("#"+allSections[i]).width()
                
                data.push({sectiontitle: allSections[i], description: "this is "+i, position: position[i].top+","+position[i].left, height: height, width: width, mediadata: allimage[i], layout_id: layout_id})
            }

            //console.log("DATA :",data)

            //Sending each section data to the sectionController
            data.forEach((data)=>{

                post('http://localhost:3000/sections',data).then((response)=>{
                    console.log(response)
                }).catch((e)=>{
                    console.log(e)
                })
    
            })           
           

            // => Array of Objects representing Band objects with IDs set
        
            swal("Success!", "Layout Design Saved!", "success");

        }
        
        
        // FetchWrapper by sajan Dhakal
        function get(url) {
            const requestOptions = {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'same-origin',
            };
            return fetch(url, requestOptions).then(handleResponse);
        }

        // post method to call fetch API 
        function post(url, body) {
            var token = $('meta[name="csrf-token"]').attr('content');

            const requestOptions = {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/json',
                    'X-CSRF-Token': token
                },
                body: JSON.stringify(body),
            };
            return fetch(url, requestOptions);
        }

        function put(url, body) {
            const requestOptions = {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body),
            };
            return fetch(url, requestOptions).then(handleResponse);
        }
        function patch(url, body) {
            const requestOptions = {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body),
            };
            return fetch(url, requestOptions).then(handleResponse);
        }
        // prefixed with underscored because delete is a reserved word in javascript
        function _delete(url) {
            const requestOptions = {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
            };
            return fetch(url, requestOptions).then(handleResponse);
        }
        // helper functions
        function handleResponse(response) {
            return response.text().then((text) => {
                try {
                    
                    const data = text && JSON.parse(text);
                    if (!response.ok) {
                        
                        if (response.status === 401) {
                            const error = { code: response.status, detail: response.statusText };
                            return Promise.reject(error);
                        }
                        const error = {
                            code: (data && data.code) || response.status,
                            detail: (data && data.detail) || response.statusText,
                        };
                        return Promise.reject(error);
                    }
                    return data;
                } catch (e) {
                    const error = { code: 500, detail: 'something went wrong' };
                    return Promise.reject(error);
                }
            });
        }
 

This is the Section controller

class SectionsController < ApplicationController

    def create
        binding.pry
        @section = Section.new(section_params)
        respond_to do |format|
            if @section.save!
                format.html { redirect_to layouts_path, notice: "Sections Created Successfully"    }
                format.js
                format.json { render json: @section,status: :created, location: @section}
            else
                
                # format.html { render :new, alert:"Unable to create new "}
                format.json { render json: @section.errors, status: :unprocessable_entity }
            end  
        end
    end

    private
    def section_params
        params.require(:section).permit(:sectiontitle,:description, :position,:height,:width,:mediadata,:layout_id)
    end
    
end

mardi 24 août 2021

Turn ruby hash into local variable

{"string_1.0" => "1,0"}
  1. In the above mentioned the ruby hash, now i want to turn hash key into local variable.
  2. Use hash key string as it is to turn into local variable.
  3. it should run with ruby instead of jruby
  4. Expected output:
string_1.0 = "1.0"

Thanks in advance for solutions.

Fail to update info user

I want to update the info user using user.update_attributes but it stated the argument error. Is it because i forgot to define the user. i forgot to define the userI also tried to user.delete but still same error

dimanche 22 août 2021

Unable to install json version 1.8.2 gem for Ruby version 2.5.3 on Ubuntu 20.04

I am trying to run a rails server and when I run the bundle install command, I get the following error:

An error occurred while installing json (1.8.3), and Bundler cannot
continue.
Make sure that `gem install json -v '1.8.3' --source 'https://rubygems.org/'`
succeeds before bundling.

When I run the recommended command gem install gem install json -v '1.8.3' --source 'https://rubygems.org/', I get error building native extensions

Building native extensions. This could take a while...
ERROR:  Error installing json:
    ERROR: Failed to build gem native extension.

    current directory: /home/user/.rvm/gems/ruby-2.5.3/gems/json-1.8.3/ext/json/ext/generator
/home/user/.rvm/rubies/ruby-2.5.3/bin/ruby -I /home/user/.rvm/rubies/ruby-2.5.3/lib/ruby/site_ruby/2.5.0 -r ./siteconf20210822-103903-1kc2ys9.rb extconf.rb
creating Makefile

current directory: /home/user/.rvm/gems/ruby-2.5.3/gems/json-1.8.3/ext/json/ext/generator
make "DESTDIR=" clean

current directory: /home/user/.rvm/gems/ruby-2.5.3/gems/json-1.8.3/ext/json/ext/generator
make "DESTDIR="
compiling generator.c
generator.c: In function ‘generate_json’:
generator.c:861:25: error: ‘rb_cFixnum’ undeclared (first use in this function); did you mean ‘mFixnum’?
  861 |     } else if (klass == rb_cFixnum) {
      |                         ^~~~~~~~~~
      |                         mFixnum
generator.c:861:25: note: each undeclared identifier is reported only once for each function it appears in
generator.c:863:25: error: ‘rb_cBignum’ undeclared (first use in this function); did you mean ‘mBignum’?
  863 |     } else if (klass == rb_cBignum) {
      |                         ^~~~~~~~~~
      |                         mBignum
generator.c: At top level:
cc1: warning: unrecognized command line option ‘-Wno-self-assign’
cc1: warning: unrecognized command line option ‘-Wno-constant-logical-operand’
cc1: warning: unrecognized command line option ‘-Wno-parentheses-equality’
make: *** [Makefile:242: generator.o] Error 1

make failed, exit code 2

I don't know how do I go about solving this, any help would be much appreciated

mercredi 18 août 2021

Parse a string json that contain another json string

I have a json which has another json inside it. But it is inside double quotes due to this it is given me a parsing error. Is there any way to parse this json

obj="{"Name":"{"FirstName":"Douglas","LastName":"Crockford"}"}" I want it like this after parsing

{Name:{FirstName:"Douglas",LastName:"Crockford"}} Is there any way to achieve this using Ruby?

Parse a json that contain json string

I have a json which has another json inside it. But it is inside double quotes due to this it is given me a parsing error. Is there any way to parse this json other than useing gsub to replage double quote..

obj={Name:"{"FirstName":"Douglas","LastName":"Crockford"}"}

I want it like this

{Name:{FirstName:"Douglas",LastName:"Crockford"}}

Is there any way to achieve this using Ruby

dimanche 15 août 2021

Ruby Heroku Deployment Error : The page you were looking for doesn't exist

Heroku App is deployed, and opened the url and an error appears saying "The page you were looking for doesn't exit". I'm looking at heroku logs, but I have no idea what I need to do and run heroku config to fix and successfully build heroku app. I see 5 build failed highlighted in red. Please help. If you need more details, please let me know by comments, I can provide more info.

What I did:

  1. I ran git push heroku master.

outcome > Verifying deploy... done. To https://git.heroku.com/<my_heroku_app>.git

  1. I ran heroku open.

outcome > The page you were looking for doesn't exist.

  1. I ran heroku logs .

outcome >

2021-08-15T15:24:08.737628+00:00 app[api]: Initial release by user janie.lee.inquire@gmail.com
2021-08-15T15:24:08.737628+00:00 app[api]: Release v1 created by user janie.lee.inquire@gmail.com
2021-08-15T15:24:08.977251+00:00 app[api]: Enable Logplex by user janie.lee.inquire@gmail.com
2021-08-15T15:24:08.977251+00:00 app[api]: Release v2 created by user janie.lee.inquire@gmail.com
2021-08-15T15:24:15.000000+00:00 app[api]: Build started by user janie.lee.inquire@gmail.com
2021-08-15T15:24:19.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/3a8bdea5-7a91-4217-aef0-82f0f3614769/activity/builds/6cd3dfbe-7004-44a7-b36f-f8a66d392183
2021-08-15T15:28:32.000000+00:00 app[api]: Build started by user janie.lee.inquire@gmail.com
2021-08-15T15:28:36.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/3a8bdea5-7a91-4217-aef0-82f0f3614769/activity/builds/c06f179f-874f-4504-9d1c-a9c11f711989
2021-08-15T15:29:19.000000+00:00 app[api]: Build started by user janie.lee.inquire@gmail.com
2021-08-15T15:29:22.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/3a8bdea5-7a91-4217-aef0-82f0f3614769/activity/builds/e37db166-e94a-4772-b763-ca52248a9778
2021-08-15T15:30:58.000000+00:00 app[api]: Build started by user janie.lee.inquire@gmail.com
2021-08-15T15:31:01.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/3a8bdea5-7a91-4217-aef0-82f0f3614769/activity/builds/23bea9c2-2c89-4a53-8951-f589c0d3f677
2021-08-15T15:32:35.000000+00:00 app[api]: Build started by user janie.lee.inquire@gmail.com
2021-08-15T15:35:50.609318+00:00 app[api]: Set LANG, RACK_ENV, RAILS_ENV, RAILS_LOG_TO_STDOUT, RAILS_SERVE_STATIC_FILES, SECRET_KEY_BASE config vars by user janie.lee.inquire@gmail.com
2021-08-15T15:35:50.609318+00:00 app[api]: Release v3 created by user janie.lee.inquire@gmail.com
2021-08-15T15:35:51.899208+00:00 app[api]: Running release v4 commands by user janie.lee.inquire@gmail.com
2021-08-15T15:35:51.899208+00:00 app[api]: Attach DATABASE (@ref:postgresql-cubed-41528) by user janie.lee.inquire@gmail.com
2021-08-15T15:35:51.910765+00:00 app[api]: @ref:postgresql-cubed-41528 completed provisioning, setting DATABASE_URL. by user janie.lee.inquire@gmail.com
2021-08-15T15:35:51.910765+00:00 app[api]: Release v5 created by user janie.lee.inquire@gmail.com
2021-08-15T15:35:52.229496+00:00 app[api]: Deploy 0d73cf03 by user janie.lee.inquire@gmail.com
2021-08-15T15:35:52.229496+00:00 app[api]: Release v6 created by user janie.lee.inquire@gmail.com
2021-08-15T15:35:52.244958+00:00 app[api]: Scaled to console@0:Free rake@0:Free web@1:Free by user janie.lee.inquire@gmail.com
2021-08-15T15:35:56.672969+00:00 heroku[web.1]: Starting process with command `bin/rails server -p ${PORT:-5000} -e production`
2021-08-15T15:35:57.000000+00:00 app[api]: Build succeeded
2021-08-15T15:35:59.751093+00:00 app[web.1]: => Booting Puma
2021-08-15T15:35:59.751104+00:00 app[web.1]: => Rails 6.1.4 application starting in production
2021-08-15T15:35:59.751105+00:00 app[web.1]: => Run `bin/rails server --help` for more startup options
2021-08-15T15:36:00.635122+00:00 app[web.1]: Puma starting in single mode...
2021-08-15T15:36:00.635134+00:00 app[web.1]: * Puma version: 5.4.0 (ruby 3.0.2-p107) ("Super Flight")
2021-08-15T15:36:00.635135+00:00 app[web.1]: *  Min threads: 5
2021-08-15T15:36:00.635135+00:00 app[web.1]: *  Max threads: 5
2021-08-15T15:36:00.635135+00:00 app[web.1]: *  Environment: production
2021-08-15T15:36:00.635135+00:00 app[web.1]: *          PID: 4
2021-08-15T15:36:00.635359+00:00 app[web.1]: * Listening on http://0.0.0.0:47725
2021-08-15T15:36:00.640656+00:00 app[web.1]: Use Ctrl-C to stop
2021-08-15T15:36:00.891478+00:00 heroku[web.1]: State changed from starting to up
2021-08-15T15:36:04.537319+00:00 app[web.1]: I, [2021-08-15T15:36:04.537216 #4]  INFO -- : [a9f2f17c-4bf6-44d7-9a9e-ac2b991a7fdd] Started GET "/" for 69.141.41.222 at 2021-08-15 15:36:04 +0000
2021-08-15T15:36:04.537993+00:00 app[web.1]: F, [2021-08-15T15:36:04.537942 #4] FATAL -- : [a9f2f17c-4bf6-44d7-9a9e-ac2b991a7fdd]
2021-08-15T15:36:04.537994+00:00 app[web.1]: [a9f2f17c-4bf6-44d7-9a9e-ac2b991a7fdd] ActionController::RoutingError (No route matches [GET] "/"):
2021-08-15T15:36:04.537995+00:00 app[web.1]: [a9f2f17c-4bf6-44d7-9a9e-ac2b991a7fdd]
2021-08-15T15:36:04.538362+00:00 heroku[router]: at=info method=GET path="/" host=enigmatic-lowlands-26772.herokuapp.com request_id=a9f2f17c-4bf6-44d7-9a9e-ac2b991a7fdd fwd="69.141.41.222" dyno=web.1 connect=1ms service=10ms status=404 bytes=1902 protocol=https
2021-08-15T15:36:04.758310+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=enigmatic-lowlands-26772.herokuapp.com request_id=f51ed3ec-b9fc-48f5-8596-d2adcf0ef3c3 fwd="69.141.41.222" dyno=web.1 connect=0ms service=1ms status=200 bytes=143 protocol=https
2021-08-15T15:42:08.000000+00:00 app[api]: Build started by user janie.lee.inquire@gmail.com
2021-08-15T15:42:13.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/3a8bdea5-7a91-4217-aef0-82f0f3614769/activity/builds/3cbb9cda-f8d0-432d-ad4e-932b7555ad7e
2021-08-15T15:43:14.000000+00:00 app[api]: Build started by user janie.lee.inquire@gmail.com
2021-08-15T15:44:32.732378+00:00 app[api]: Release v7 created by user janie.lee.inquire@gmail.com
2021-08-15T15:44:32.732378+00:00 app[api]: Deploy ba4e17de by user janie.lee.inquire@gmail.com
2021-08-15T15:44:33.304080+00:00 heroku[web.1]: Restarting
2021-08-15T15:44:33.328955+00:00 heroku[web.1]: State changed from up to starting
2021-08-15T15:44:34.047751+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2021-08-15T15:44:34.131374+00:00 app[web.1]: - Gracefully stopping, waiting for requests to finish
2021-08-15T15:44:34.132077+00:00 app[web.1]: Exiting
2021-08-15T15:44:34.196707+00:00 heroku[web.1]: Process exited with status 143
2021-08-15T15:44:37.000000+00:00 app[api]: Build succeeded
2021-08-15T15:44:37.713582+00:00 heroku[web.1]: Starting process with command `bin/rails server -p ${PORT:-5000} -e production`
2021-08-15T15:44:40.917363+00:00 app[web.1]: => Booting Puma
2021-08-15T15:44:40.917375+00:00 app[web.1]: => Rails 6.1.4 application starting in production
2021-08-15T15:44:40.917375+00:00 app[web.1]: => Run `bin/rails server --help` for more startup options
2021-08-15T15:44:41.875499+00:00 app[web.1]: Puma starting in single mode...
2021-08-15T15:44:41.875524+00:00 app[web.1]: * Puma version: 5.4.0 (ruby 3.0.2-p107) ("Super Flight")
2021-08-15T15:44:41.875524+00:00 app[web.1]: *  Min threads: 5
2021-08-15T15:44:41.875525+00:00 app[web.1]: *  Max threads: 5
2021-08-15T15:44:41.875525+00:00 app[web.1]: *  Environment: production
2021-08-15T15:44:41.875525+00:00 app[web.1]: *          PID: 4
2021-08-15T15:44:41.875788+00:00 app[web.1]: * Listening on http://0.0.0.0:45606
2021-08-15T15:44:41.881623+00:00 app[web.1]: Use Ctrl-C to stop
2021-08-15T15:44:41.986244+00:00 heroku[web.1]: State changed from starting to up
2021-08-15T15:44:44.379999+00:00 app[web.1]: I, [2021-08-15T15:44:44.379919 #4]  INFO -- : [ea8757ee-3e31-4fd3-bf8b-a80565ff6c1c] Started GET "/" for 69.141.41.222 at 2021-08-15 15:44:44 +0000
2021-08-15T15:44:44.380434+00:00 app[web.1]: F, [2021-08-15T15:44:44.380402 #4] FATAL -- : [ea8757ee-3e31-4fd3-bf8b-a80565ff6c1c]
2021-08-15T15:44:44.380434+00:00 app[web.1]: [ea8757ee-3e31-4fd3-bf8b-a80565ff6c1c] ActionController::RoutingError (No route matches [GET] "/"):
2021-08-15T15:44:44.380435+00:00 app[web.1]: [ea8757ee-3e31-4fd3-bf8b-a80565ff6c1c]
2021-08-15T15:44:44.382101+00:00 heroku[router]: at=info method=GET path="/" host=enigmatic-lowlands-26772.herokuapp.com request_id=ea8757ee-3e31-4fd3-bf8b-a80565ff6c1c fwd="69.141.41.222" dyno=web.1 connect=0ms service=8ms status=404 bytes=1902 protocol=https
2021-08-15T15:44:44.437773+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=enigmatic-lowlands-26772.herokuapp.com request_id=419e8623-a3fe-41a6-b619-31964b35fa29 fwd="69.141.41.222" dyno=web.1 connect=0ms service=1ms status=200 bytes=143 protocol=https

github of this project https://github.com/janie-lee-developer/hek

how do i acheive this same result using Active Query Methods?

this is what i want to achieve using active query method i was asked not to do array iterations but instead use active query methods to achieve this

         def index
            @measurements = current_user.measurements.with_units.created_on
            data = Hash.new { |h, k| h[k] = [] }
            @measurements.each do |m|
              data[m.unit.title] << m
            end
            render json: { data: data, status: :ok }
          end`
        

and here are my models for Measurement and Units

        class Measurement < ApplicationRecord
          belongs_to :user
          belongs_to :unit
          scope :with_units, -> { includes(:unit) }
          scope :created_on, -> { order('created_at DESC') }
        
          validates :value, presence: true
        end
        
        Model for Units
        class Unit < ApplicationRecord
          has_many :measurements
        
          scope :with_measurements, -> { includes(:measurements) }
          scope :with_user_id, ->(user) { where(user_id: user.id) }
        
          validates :title, presence: true
        end
    
    Schema table for measurements
    
      create_table "measurements", force: :cascade do |t|
        t.integer "unit_id"
        t.integer "user_id"
        t.float "value"
        t.datetime "created_at", precision: 6, null: false
        t.datetime "updated_at", precision: 6, null: false
      end
    
Schema table for Units 

      create_table "units", force: :cascade do |t|
        t.string "title"
        t.datetime "created_at", precision: 6, null: false
        t.datetime "updated_at", precision: 6, null: false
      end
    

samedi 14 août 2021

How can I display country code and last 3 digits of phone number in Ruby on Rails views?

I am a beginner in RoR. This is original phone number +77123456999

I am going display it as +77xxxxxx999

here is my index.html.erb file codes.

`

<tbody>
    <% @users.each do |user| %>
        <tr>
            <td>
                <%= user.username %>
            </td>
            <td>
                <%= user.phone %>
            </td>
            <td>
                <%= user.email %>
            </td>
            <td>
                <%= user.state %>
            </td>
        </tr>
    <% end %>
</tbody>

`

the value of user.phone is +77123456999 How can I change is as I want?

vendredi 13 août 2021

Ruby on Rails The kept


od_practice.partnerships.kept.first&.omd_practice&.id

I have seen people use the word kept.first to pull data from database in ruby on rail . What does these words mean ? i have tried to do some research and i seem not find any solution. Can someone explain me please ?

jeudi 12 août 2021

Value in a Hash is in another Hash Ruby

I have two hashes, one have all values, the second one have specific values that are also included in the first one. I want to create a third one that have all values of the first one but excluding the values of the second one.

Example

Hash one function:

def get_states
      States.new(
          name: :All,
          dimensions: all_states)
 end

def isolated_states
      get_states.dimensions.select {|d| d.isolate_code?}
    end

Then here I want to do something like

states: get_states.select{|d| d.include(isolates_states)}

FinalStage.new(name: state_name, states: get_states)

No such middleware to insert after: "ActionDispatch::DebugExceptions"

Recently I have migrated an Old Ruby Project (Ruby 2.2.5, Rails 4.2.7.1) to the latest version.

I followed the below steps to do this,

  1. Deleted the GEM.lock File
  2. Removed the version numbers in the GEM file
  3. Reran "bundle install" command.

Now I am unable to run "rake db:migrate" command as it is throwing me the below error.

rake aborted!
No such middleware to insert after: "ActionDispatch::DebugExceptions"

But other projects in my repo ran successfully. I tried the "bundle exec rake db:migrate" command instead of "rake db:migrate" command. But didn't help.

I get the same error when I run

rake middleware

My current versions are Ruby 2.6.7 and Rails 6.1.4

Please help me.

lundi 9 août 2021

Auto scale a delayed job server Rails?

I have a Ruby on Rails application and that is using delayed jobs.

gem 'delayed_job', '4.1.8'

I want to auto-scale the server running the delayed jobs. But by AWS convention it is going to terminate the delayed job server is the load on CPU is less than a threshold value even is it is having a delayed job still executing on it. I do not want it to happen. can any body suggest the strategy to be used in this place.

I want it like is no. of delayed jobs > threshold spin new server instance with delayed job worker then the jobs and let them execute. if the delayed_jobs locked by a specific a host host goes 0 then terminate that delayed server.

dimanche 8 août 2021

Decimal values are truncating with to_f

I have model called Item, where I am updating the unit_price (Data Type is Decimal) value, currently I am not putting any limit when storing the value, storing the value as it is. But now I can see this PG error PG::NumericValueOutOfRange, when the value exceeds the limit.

So I was just trying to limit the value and checking something in the console, Below is the data. (Here in the data I am not putting all the decimal values)

#<Item id: 167199, description: "192830139", category_id: 10327, unit_id: 5596, weight: 0.1e5, unit_price: 0.4083333333659917816764132553606237816656920077972709552126705653021442494641325536062378168e1

i = Item.find 167199

i.unit_price.to_f
=> 4.083333333659918

#<Item id: 167199, description: "192830139", category_id: 10327, unit_id: 5596, weight: 0.1e5, unit_price: 0.6511366980197836882065909262763993442019943880913510722934069011050182329156169820243980265070876781866034494363303661586489199452739290976143216266200531728395970406461889852558384421962422689303402903e-2

i.unit_price.to_f
=> 0.006511366980197837

Can I know what will be the reason this data shows like truncated after I apply to_f ? What will be best way to solve this issue, I was just thinking about some truncate with some limit.

how to start rails rake tasks in kubernetes cron job

We are deploying a Rails application on Kubernetes.

The assets:precompile task run as part of the Docker image build process.

We want to run rake tasks like rake db:migrate task and other tasks on each deployment.

Current solution, we are using kubectl exec.

deplyment.yaml

apiVersion: extensions/v1
kind: Deployment
metadata:
  name: rails-app
spec:
  template:
    spec:
      containers:
        - image: test/rails-app:v0.0.1
          name: myapp
          imagePullPolicy: IfNotPresent

Get list of pods

$ kubectl get pods

Then exec on the rails pod:

$ kubectl exec rails-app-4007005961-1st7s                              \
          -- bash -c                                               \
          'bin/rake db:migrate

'

We need to use kubernentes cronjob (.yaml) to start our rake taks but we do not know which docker image we must use ? how to connect to rails pod and start the rake task ?. example of implementation ?

vendredi 6 août 2021

How to find the number of delayed jobs currently enqueued and working?

In rails application.To check total number of jobs:

Delayed::Job.all.length

Now How to check number of jobs enququed but not working and no of jobs working in delayed job rails. Thanks in advance.

jeudi 5 août 2021

TO answer is

"""<%= button_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %>"""

mercredi 4 août 2021

Validation issues with HTML tags

The database saves the HTML tags from the input form and I would like to strip them to do correct validation. I tested the below method in IRB and it seems to work fine. However I cannot figure out how to use this method to do my validation.

Here's the code from my model:

class Task < ActiveRecord::Base
  validates strip_tag(:text), length: {minimum: 3}, uniqueness: true
  
  def strip_tag(record)
    record.split(/\<.*?\>/).map(&:strip).reject(&:empty?).join(' ').gsub(/\s,/,',')
  end
end

The issue I am facing is that am checking for uniqueness and the length to be greater than 3, but because of the HTML tags it's easy to create duplicates for example.

Example of a duplication after remove tags:

"<p><span style=\"color: #1d3d70; font-family: -apple-system, system-ui, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; font-size: 16px; background-color: #ffffff;\">Testing 8449</span></p>" 

and this one:

"<p>Testing 8449</p>" 

Both should have the same values after removing the HTML tags and I want to prevent this duplicates for example.

dimanche 1 août 2021

Ransack filtering on custom fields

I have a Data::Users with object types:

  id: "0e00392b-4205-43d1-8969-b6c7f2a92d8b",
  identifier: "bb7b38dc-bc21-4386-98a4-8d9738c11d5c",
  properties:
   {"name"=>"Vern Lueilwitz",
    "email"=>"carmen@altenwerth-batz.org",
    "last_time_entry_on"=>"2021-06-26",
    "liked_videos_count"=>201,
    "played_videos_count"=>609,
    "viewed_photos_count"=>143},
  created_at: Sat, 31 Jul 2021 17:24:48.836493000 UTC +00:00,
  updated_at: Sat, 31 Jul 2021 17:24:48.836493000 UTC +00:00,

When I try:

 Data::User.ransackable_attributes

I get the fields : ["id", "identifier", "created_at", "updated_at", "properties"]

The properties is a custom json which can contain any key and value. It is fetched from another server. I want to be able to ransack those custom fields. Any way I can extend ransack to allow filtering on those fields which are not on my table?