Rubocop loading issue on VScode

If you are facing issue to load rubocop plugin to your VS code try the following steps to fix it.

The error message will be something like:

rubocop on VScode not working.Error “rubocop is not executable”

  1. First you have to ensure that you have installed ruby in your machine. if you are using docker containers for your project, ruby is installed inside the containers and VS Code cannot find it.
  2. Next install rubocop gem in your machine
                 $ gem install rubocop

3. Next take

  VS Code -> Settings -> search for 'rubocop' in Ruby > Rubocop: Execute Path

add the output of the following command:

        $ which rubocop

4. Reload the rubocop plugin from VS Code.

Now VS Code will get to execute rubocop.

Backup your system databases using Ruby backup gem

Install RVM (Or Rbenv) to manage your Ruby versions

 $ gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
 $ curl -sSL https://get.rvm.io | bash 

Restart Terminal and type rvm -v

 $ rvm install 2.5
 $ rvm gemset create backup
 $ rvm gemset use backup
 $ gem install backup
 $ backup generate:model --trigger project_2_backup --archives --storages='s3' --compressor='gzip' --notifiers='mail' 
 Generated configuration file: '/home/ubuntu/Backup/config.rb'.
 Generated model file: '/home/ubuntu/Backup/models/project_2_backup.rb'.
 Usage:
   backup generate:model --trigger=TRIGGER
 Options:
   --trigger=TRIGGER
   [--config-path=CONFIG_PATH]  # Path to your Backup configuration directory
   [--databases=DATABASES]      # (mongodb, mysql, postgresql, redis, riak)
   [--storages=STORAGES]        # (cloudfiles, dropbox, ftp, local, ninefold, rsync, s3, scp, sftp)
   [--syncers=SYNCERS]          # (cloud_files, rsync_local, rsync_pull, rsync_push, s3)
   [--encryptors=ENCRYPTORS]    # (gpg, openssl)
   [--compressors=COMPRESSORS]  # (bzip2, gzip, lzma, pbzip2)
   [--notifiers=NOTIFIERS]      # (campfire, hipchat, mail, presently, prowl, twitter)
   [--archives]
   [--splitter]                 # use `--no-splitter` to disable
                               # Default: true 

Sample Model File

Add the following conf in Backup/models/project_2_backup.rb:

Example for mongodb

 database MongoDB do |db|
     db.name               = "db_name"
     db.username           = "db_username"
     db.password           = "db_pswd"
     db.host               = "localhost"
     db.port               = 27017 
     db.ipv6               = false
     #db.only_collections   = ["only", "these", "collections"]
     db.additional_options = ['--authenticationDatabase=admin']
     db.lock               = false
     db.oplog              = false
   end
   ## 
   # Amazon Simple Storage Service [Storage]
   #
   store_with S3 do |s3|
     # AWS Credentials
     s3.access_key_id     = "YOUR_ACCESS_KEY"
     s3.secret_access_key = "YOUR_SECRET_KEY"
     # Or, to use a IAM Profile:
     # s3.use_iam_profile = true
     s3.region            = "ap-southeast-2" 
     s3.bucket            = "bucket_name"
     s3.path              = "bucket_name_path"
     s3.keep              = 12
     # s3.keep              = Time.now - 2592000 # Remove all backups older than 1 month.
   end 

 # Notification mail infos
 notify_by Mail do |mail|
     mail.on_success           = true
     mail.on_warning           = true
     mail.on_failure           = true
     mail.from                 = "_____@gmail.com"
     mail.to                   = "____@___.com"
     mail.cc                   = "______@_____.com, _____@______.com"
     #mail.bcc                  = "bcc@email.com"
     #mail.reply_to             = "reply_to@email.com" 
     mail.address              = "smtp.gmail.com"
     mail.port                 = 587
     mail.domain               = "domain_name"
     mail.user_name            = "email_username"
     mail.password             = "email_password"
     mail.authentication       = "plain"
     mail.encryption           = :starttls
 end 

Once you’ve setup your configuration, check your work with:

$ backup check

If there are no errors, the check should report:

[2019/03/28 10:02:26][info] Configuration Check Succeeded.

Perform Backup:

$ backup perform --trigger project_2_backup

The Keep Option

keep a specified number of backups in storage. After each backup is performed, it will remove older backup package files based on the keep setting.

keep as a Number

If a number has been specified and once the keep limit has been reached, the oldest backup will be removed.

Note that if keep is set to 5, then the 6th backup will be transferred and stored, before the oldest is removed. So be sure you have space available for keep + 1 backups

keep as Time

When a Time object is set to keep it will keep backups until that time. Everything older than the set time will be removed.

install JRE/JDK on ubuntu 16.06

For Mac system Download ‘dmg’ file from here and double click on it.

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

For Linux: 

Don’t install OpenJDK

 $ sudo apt update && sudo apt install openjdk-9-jre-headless
 $ java -version
 openjdk version "9-internal"
 OpenJDK Runtime Environment (build 9-internal+0-2016-04-14-195246.buildd.src)
 OpenJDK 64-Bit Server VM (build 9-internal+0-2016-04-14-195246.buildd.src, mixed mode) 

Install Oracle Java:

 $ sudo add-apt-repository ppa:webupd8team/java
 $ sudo apt-get update
 $ sudo apt-get install oracle-java8-installer
 $ java -version
 java version "1.8.0_171"
 Java(TM) SE Runtime Environment (build 1.8.0_171-b11)
 Java HotSpot(TM) 64-Bit Server VM (build 25.171-b11, mixed mode) 

After installing Java on Linux system, You must have to set JAVA_HOME and JRE_HOME environment variables. Which is used by many Java applications to find Java libraries during runtime. You can set these variables in /etc/environment file using the following command.

 cat >> /etc/environment <<EOL
 JAVA_HOME=/usr/lib/jvm/java-8-oracle
 JRE_HOME=/usr/lib/jvm/java-8-oracle/jre
 EOL 

Enable MongoDB Access Control

The default data directory for MongoDB is /data/db

This can be overridden by a dbpath option specified on the command line or in a configuration file.

If you install MongoDB via a package manager such as Homebrew or MacPorts these installs typically create a default data directory other than /data/db and set the dbpath in a configuration file.

You can check the dbpath by:

db.serverCmdLineOpts()

in your mongo shell

 "storage" : {
    "dbPath" : "/usr/local/var/mongodb"
 }, 

The following procedure first adds a user administrator to a MongoDB instance running without access control and then enables access control.

1.  Start MongoDB without access control.

$ mongod --port 27017 --dbpath /data/db1

2. Connect to the instance.

$ mongo --port 27017

3. Create the user administrator.

In the admin database, add a user with the userAdminAnyDatabase role. For example, the following creates the user myUserAdmin in the admin database:

Note: The database where you create the user (in this example, admin) is the user’s authentication database.

 > db.createUser(
 ...   {
 ...     user: "abhilash",
 ...     pwd: “password!“,
 ...     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
 ...   }
 ... ) 

 Successfully added user: {
 "user" : "abhilash",
 "roles" : [
  {
    "role" : "userAdminAnyDatabase",
    "db" : "admin"
  }
 ]
 } 

Disconnect the mongo shell.

4. Re-start the MongoDB instance with access control.

$ mongod --auth --port 27017 --dbpath /usr/local/var/mongodb/db1

Clients that connect to this instance must now authenticate themselves as a MongoDB user.

 > db.auth();
 Error: auth expects either (username, password) or ({ user: username, pwd: password })
 0
 > db
 test 

** To authenticate during connection:

$ mongo --port 27017 -u "abhilash" -p "password!” --authenticationDatabase "admin"

** To authenticate after connecting

Connect the mongo shell

 $ mongo
 > use admin
 > db.auth("abhilash", “password!“ )
 > mongo
 MongoDB shell version v3.4.7
 connecting to: mongodb://127.0.0.1:27017
 MongoDB server version: 3.4.7
 Server has startup warnings:
 2018-01-22T10:32:18.027+0530 I CONTROL  [initandlisten]
 2018-01-22T10:32:18.027+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
 2018-01-22T10:32:18.027+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
 2018-01-22T10:32:18.027+0530 I CONTROL  [initandlisten]
 > use admin
 switched to db admin
 > db
 admin
 > db.auth("abhilash", "password!”);
 1
 > use my_dbname;
 > db.createUser(
   {
     user: "vadmin",
     pwd: “pass111!”,
     roles: [ { role: "readWrite", db: "my_dbname" },
              { role: "read", db: "test" } ]
   }
 ) 

Reference:  Mongodb enable-authentication 

A Ruby on Rails Application without models

This blog is a quick walkthrough of creating a Ruby On Rails application without a model.

Find Rails new options from here:
https://gist.github.com/abhilashak/3c0c62fa62b2f7a439c417b68d032575

Find Gemfile options from here:

http://bundler.io/v1.2/gemfile.html

Install Ruby/Rails using rbenv

$ touch .rbenv-gemsets
$ echo project-name > .rbenv-gemsets
$ rbenv gemset active
$ rbenv install 2.5.3
$ gem install bundler
$ rbenv rehash
$ gem install rails -v 5.2.9
$ rbenv rehash
$ rails new my-new-porject --skip-active-record --skip-bundle -v 5.2.9

Add in Gemfile:

ruby “2.5.3”

comment jbuilder, we don’t need it.

# gem 'jbuilder', '~> 2.8’

Move rbenv gems file to new rails app folder

$ mv .rbenv-gemsets my-new-porject

$ touch .ruby-version

$ echo 2.5.3 > .ruby-version

$ gem install bundler

$ bundle

$ ruby -v
ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-darwin18]

Start Rails server:

$ rails s

Gemfile add:

# Bootstrap Theme

gem 'bootstrap', '~> 4.3.0’

# Slim template Engine

gem 'slim', '>=4.0.1’

Do Bundle Install

$ bundle

Rename css to scss because we use bootsrap mixins and variables that work with scss files

$ mv app/assets/stylesheets/application.css app/assets/stylesheets/application.scss

Import Bootstrap styles in app/assets/stylesheets/application.scss:

// Custom bootstrap variables must be set or imported *before* bootstrap.
@import "bootstrap";

Then, remove all the *= require and *= require_tree statements from the Sass file. Instead, use @import to import Sass files.

Bootstrap JavaScript depends on jQuery
Add jquery-rails to Gemfile:

gem 'jquery-rails', '~> 4.3.4’

Bootstrap tooltips and popovers depend on popper.js for positioning.
Add Bootstrap dependencies and Bootstrap to your application.js:

//= require jquery3
//= require popper
//= require bootstrap-sprockets

While bootstrap-sprockets provides individual Bootstrap components for ease of debugging, you may alternatively require the concatenated bootstrap for faster compilation:

//= require jquery3
//= require popper
//= require bootstrap

Sass: Individual components

All Bootstrap opponents will be imported by default.
You can also import components explicitly. To start with a full list of modules copy _bootstrap.scss file into your assets as _bootstrap-custom.scss. Then comment out components you do not want from _bootstrap-custom. In the application Sass file, replace @import ‘bootstrap’ with:

@import 'bootstrap-custom';

Your application.css:

/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 */

/*Custom bootstrap variables must be set or imported *before* bootstrap.
  The available variables can be found: 
  https://github.com/twbs/bootstrap-rubygem/blob/master/assets/stylesheets/bootstrap/_variables.scss
*/
@import "bootstrap";

Your application.js File:

// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require turbolinks
//= require_tree .
//= require jquery3
//= require popper
//= require bootstrap-sprockets

You can check sample bootstrap forms here:

https://bootsnipp.com/snippets/featured/login-amp-signup-forms-in-panel

Remove cable.js from javascripts # we don’t need this for now

Rails 5.2.0 API Only application with latest Ruby 2.5.1

Check for the new ruby and rails versions
https://www.ruby-lang.org/en/downloads/
https://rubygems.org/gems/rails/versions

Here we are going to install Ruby – 2.5.1 & Rails – 5.2.0 (API only application)

Get rbenv into action
If you are not installed rbenv, you can install it from here:
https://github.com/rbenv/rbenv
After the installation make sure that, your $PATH has included rbenv/shims path. Else rbenv will not work.

1. $ rbenv install --list # Gets the list of ruby versions available

$ rbenv install 2.5.1

ruby-build: definition not found: 2.5.1

The following versions contain `2.5.1' in the name:
  rbx-2.5.1

See all available versions with `rbenv install --list'.

If the version you need is missing, try upgrading ruby-build:

  brew update && brew upgrade ruby-build

Oops..!

rbenv cannot find the version: 2.5.1

Upgrade ruby-build

Mac OSX:

$ brew upgrade ruby-build --HEAD

Now install ruby 2.5.1

$ rbenv install 2.5.1

Create a new gemset:

Rbenv gemset is a separate script and not coming with rbenv. If you are not installed this, you can install it from here:
https://github.com/jf/rbenv-gemset

$ rbenv gemset create 2.5.1 demo-app
That set up a directory for you in ~/.rbenv/versions/2.5.1/gemsets/demo-app

Set the ruby version to the newest

$ rbenv local 2.5.1

$ rbenv version
=> 2.5.1

    Activate New Gemset


For activating a gemset we need to create a .rbenv-gemsets file in the current directory.

$ touch .rbenv-gemsets
$ echo demo-app > .rbenv-gemsets

Check active gemset:

$ rbenv gemset active

Install Rails 5.2.0 API only Application

$ gem install rails -v '5.2.0'

$ rails -v
Rails 5.2.0

Later we can delete this .rbenv-gemsets file and add a new file named ‘.ruby-gemset’ in the rails project directory. I cannot find any other option for doing this. If anyone know more about this, please give a comment. I appreciate that.

Create a New Rails app

$ rails new demo-app  --api -T # API only skip the testing framework altogether

For Full Rails:

$ rails new demo-app -T -d postgresql # skip the testing framework altogether, uses Postgres Database

-T to exclude Minitest – the default testing framework if you are planning to use RSpec to test your API.

Rspec test framework:
https://github.com/rspec/rspec-rails

You can use the following with Rspec.
Shoulda Matchers:
Collection of testing matchers extracted from Shoulda (http://matchers.shoulda.io)
https://github.com/thoughtbot/shoulda-matchers

Database Cleaner:
Strategies for cleaning databases in Ruby. Can be used to ensure a clean state for testing
https://github.com/DatabaseCleaner/database_cleaner

Faker:
A library for generating fake data such as names, addresses, and phone numbers.
https://github.com/stympy/faker

use option: –no-rdoc –no-ri # skips the documentation

Remove Rbenv Gemset and add Ruby gems file

$ rm .rbenv-gemsets

$ cd demo-app
$ touch .ruby-gemset
$ echo demo-app > .ruby-gemset
$ rails s
=> Booting Puma
=> Rails 5.2.0 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.11.4 (ruby 2.5.1-p57), codename: Love Song
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

Goto http://localhost:3000/

rails-5.2.api-application

Done! Lets go…

Install Learning Locker (NodeJS) in your Mac OSX

Visit the following link to install LL on CentOS, Fedora, Ubuntu, and Debian OS
http://docs.learninglocker.net/guides-installing/

Mac OS is not supported in the installation process specified above.

You can install Learning Locker in Mac OSX by custom installation.

Steps to Install LL in Mac OSX:

1. Clone the repo from learning locker git repo

$ git clone https://github.com/LearningLocker/learninglocker.git

Enter into the directory and install the requirements:

$ yarn install

You can be built 5 distinct services with this codebase.
2. Install services

If you want to install all services on the same machine, you can use the following one command:
$ yarn build-all

Install Services separately if you want to install each service in different servers

Install the UI Server
$ yarn build-ui-server

Install the UI Client
$ yarn build-ui-client

Install the API Server
$ yarn build-api-server

Install the Worker
$ yarn build-worker-server

Install CLI
$ yarn build-cli-server

Note: Copy the .env.example into a new .env file and edit as required

RUNNING THE SERVICES VIA PM2

Install pm2 , if you have not yet installed
$ npm i -g pm2

To start API, Scheduler, UI, Worker services, navigate to the LL working directory and run:

$ pm2 start pm2/all.json

INSTALLING THE XAPI SERVICE

Step 1: Clone the repo
$ git clone https://github.com/LearningLocker/xapi-service.git

Step 2: Enter into the directory and install the requirements and build

$ yarn install
$ yarn build

Note: Copy the .env.example into a new .env file and edit as required

To start the xAPI service, navigate to the xAPI Service working directory and run:

$ pm2 start pm2/xapi.json

You can check the service status:

$ pm2 status

$ pm2 restart all # restart all services

$ pm2 logs # view logs

Launch the UI:
http://localhost:3310/login, note that I have change the UI port in .env to 3310, as other services running in default port

TheLearningLockerMac

Now you have to create User for logging in. Lets create an Admin User by the following command.

$ node cli/dist/server createSiteAdmin [email] [organisation] [password]

In order to use this command you have to install the CLI server for LL, that I already mentioned in the installation steps.

An Admin Example
$ node cli/dist/server createSiteAdmin "MyEmailId" "CoMakeIT" “myPassword”

You can run the migrations by the following command if any pending migrations exists

$ node cli/dist/server migrateMongo

LL-sign-in-error

Now try to Login with the credentials.

Ooops… there is an issue, and we can’t login

After doing some research I found the issue. We need to add a secret key base to our Application to work with JWT tokens.
Open .env file and find:

# Unique string used for hashing
# Recommended length, 256 bits
APP_SECRET=

Create a 256 bit length hash key and give as a value. As I am a Rails developer, It is easy for me to create one by going into any my Rails project and type

$ rake secret

I get One! 🙂

Or you can use some online applications like: https://randomkeygen.com/

And do:
$ pm2 restart all

from LL project folder

LL-dashboard

Try to sign in again

Wohh, Its done. Great. Now you can try some bit of dashboard items like Graphs. Go on.