17 October 2017

Important features and of C programming language


  1. Function prototype declaration. Like declaring a variable in java, you can also declare a function. It is useful if you are going to call the function before the definition of the function. 
  2. C has pointer operator.
  3. C doesn't have a string data type. Instead we can use char array. 
  4. Structure is a custom data type. It's kind of an "object".
  5. "%lf" to format double
  6. "%.2f" to format float with 2 digit after a comma. 
  7. "%d" to format an integer. 
  8.  Store only positiv integer value: unsigned int a;
  9. int A[4], printf("%d\n", A); will return the base address (Address of first element)
  10. int A[4]; A[0] = 3;  printf("%d\n", A*); will return the value of the first element.
  11. Casting an Array to a pointer, now you can access the element without brackets

12 October 2017

32 Bit & 64 Bit floating number

single precision

double precision

Source: Wikipedia

Please watch this video for better understanding

11 October 2017

Angular 4, create your own custom binding

Sometimes, you want to create your own data binding, for example to use the same properties in different components to support modular programming. If you're unfamiliar with binding and component in Angular, please check my previous post about Angular. We use data binding to bind the html file to the business logic on the typescript file. But instead of using any existing properties of the html tag like [src]="" or [(ngModel)]= "" we can create our own.

  1. create a new sub-component. You can create it manually or using cli command: ng g c yourComponent --spec false. Now you can use the <app-yourComponent> tag in your app-component.html
  2. In the sub-component create an object you want to bind for e.g user
  3. Add @Input() decorator before the object declaration
  4. your HTML file will look like this when binding element object(in serverComponent) and serverElements array(in app.component)

10 October 2017

Creating own library in C

To create your own library in C please follow this steps:


  1. Create two folders, name the first folder 'utils' and the second folder 'headers'
  2. Write your functions in a .c file and put it in the utils folder. 
  3. Create a .h file with the same name as the .c file that contains the functions. Put the header files in the headers folder. The .h file should contains following code. 
  4. Open terminal and go to the utils folder and compile the .c files using this command gcc -c *.c
  5. Build the library by putting all the .o files in an archive using this command ar -cvq yourlibraryname.a *.o library name starts with lib, and don't froget the .a extension at the end
  6. Now you can use the library in your program by adding a file header #include "headers/yourLibraryName.h"
  7. Compile your program by providing the library name gcc -o programName programSourceCode.c utils/libraryName.a
  8. If youre using C-Lion IDE, you can simply add your .c and .h paths to the CMakeList.txt like this:

3 October 2017

Angular basic knowledges, installing, adding bootstrap, and two ways data binding

  1. Untuk memulai menggunakan framework Angular, kamu harus menginstall node terlebih dahulu. Pergi ke Node browser, lalu ikuti instruksi untuk mendownload node.js
  2. Setelah itu pergi ke terminal, lalu ketik npm install -g @angular/cli untuk menginstall angular command line interface. kunjungi websitenya untuk mendapatkan informasi lebih lanjut Angular CLI
  3. untuk memulai suatu project ketik ng new <yourappname>
  4. lalu masuk ke folder applikasi kamu dengan mengetik cd <yourappname>
  5. lalu jalankan applikasi kamu dengan mengetik ng serve cek applikasi kamu dengan membuka browser dan ketik localhost:4200
  6. Untuk menambahkan bootstrap, caranya install bootstrap melalui npm npm install bootstrap --save lalu buka folder .angular-cli.json dan tambahkan di bagian "styles" "../node_modules/bootstrap/dist/css/bootstrap.min.css"
  7. Data binding satu arah dari HTML ke Business logic biasanya dilakukan menggunakan event handling <button (click) = "YourMethod()"> atau <input type="text" (input) = "YourMethod($event)">
  8. Sebaliknya, data binding satu arah dari Business logic ke HTML biasanya dilakukan menggunakan property binding <button [disabled]="sex === 'male'">
  9. Untuk melakukan komunikasi dua arah antara typescript(Business Logic) dan Template(HTML) kita bisa mengunakan data binding dua arah <input type="text" [(ngModel)] = "data">

23 September 2017

Linux Ubuntu Server Important Commands

  • Adding new user: adduser {username}
  • Adding user to sudo group (seperti administrator) gpasswd -a {username} sudo
  • Change user from root su - {username}
  • Update package dengan versi terbaru seandainya ada, atau updating packages dari repository sudo apt-get update
  • Upgrade software dengan versi terbaru sudo apt-get upgrade
  • Memberi nama kepada host (hostname) echo "{yourHostname}" > /etc/hostname
  • Editing hosts /etc/hosts file nano /etc/hosts
  • Editing local timezone dpkg-reconfigure tzdata
  • Setelah kamu menginstall MongoDB, kamu bisa men-run mongodb server dengan sudo service mongodb start
  • Untuk melihat daftar program yang sedang berjalan 'running processes' ps -ef
  • Untuk menghentkan suatu program atau running process kill {processID} atau kill -9 {processID}
  • Seandainya kamu menggunakan 'putty' untuk mengakses remote server, pasti kamu tahu bahwa ketika kita mengakhiri suatu session, maka program yang berjalan di foreground akan mati. Untuk mengakalinya, kita bisa menggunakan programm 'screen'. Setelah kamu menginstall screen sudo apt-get install screen, kamu bisa memulai screen dengan mengetik screen dan untuk keluar dari session tanpa mematikan process yang sedang berjalan kamu bisa men-detach screen dengan CTRL + A + D. untuk kembali masuk ke screen yang tadi kamu detach, kamu bisa ketik screen -r {screenID} untuk men-rettach screen tersebut

Using Retrofit to build HTTP Client on Android

Untuk berkomunikasi dengan remote server, kamu bisa menggunakan java 3th party library 'Retrofit'. Dengan library ini kamu bisa mengirim dan menerima data ke dan dari remote server dalam bentuk JSON. Retrofit adalah library favorit saya karena mudah sekali untuk menggunakannya. Disini saya akan merangkum step-step bagaimana kamu bisa menggunakan retrofit dengan cepat di project kamu

  1. Tambahkan internet permission ke dalam manifest XML file.
  2. Tambahkan Retrofit dan Gson kedalam gradle build file
  3. Buat Object class yang akan di kirim atau di terima sebagai JSON file, jangan lupa bahwa semua fieldnya harus di declared dengan tipe String
  4. Buat ApiClient class
  5. Definisikan API Interface
  6. Gunakan ApiClient di Aplikasi kamu

Terkadang kamu harus membuat suatu class tambahan yang bisa menampung respon object dari server. Misal, kamu mengirim ("POST") user data melalui User object, akan tetapi jawaban (respond) dari server memiliki properties yang berbeda dari User class. Kamu bisa membuat Class Result yang bisa menampung respon dari server kemudian kamu bisa menambahkan Result Object kedalam Class User. Tool yang saya pakai untuk membuat Result class ini adalah JsonSchemaToPOJO Caranya mudah, masukan respon (JSON) yang kamu dapatkan dari aplikasi POSTMAN kedalam formular yang ada di Json2Pojo.

22 September 2017

NPM modules for a simple web application

  1. Express
  2. Nodejs backend framework untuk applikasi web. Memudahkan kamu untuk menghandle routes, get and post requests. untuk menginstall ketik npm install express --save
  3. Handlebar
  4. Adalah javascript templating engine dengan syntax yang sangat simple. Dengan menggunakan syntax {{yourObjectProperty}}. Untuk mengkombinasikan express.js dan handlebars.js kamu harus menginstall hbs packaged module dari npm. npm install hbs --save
  5. Nodemon
  6. Request
  7. Yargs
  8. Mongoose
  9. Body-parser
  10. Lodash
  11. validator
  12. jsonwebtoken
  13. bcrypt

20 September 2017

MongoDB important commands

  • Setelah kamu sukses menginstall MongoDB, kamu bisa masuk ke 'bin' directory dimana MongoDB diinstall. Di Windows biasanya directory ini berada di C:\Program Files\MongoDB\Server\YourMongoDBVersion\bin didalamnya kamu bisa menyalakan db server dengan mengetik mongod.exe --dbpath \Masukan\Path\Folder\pilihan\kamu lalu tekan enter.
  • Kalian bisa berkomunikasi dengan database dengan men-run mongo.exe di bin directory, atau dengan menggunakan mongo UI 'Robo 3T' (formerly 'Robomongo')

Node important commands

Starting a Project

Untuk memulai node project kita harus membuat directory, dan melalui command line, kita masukan npm init untuk memulai sebuah node project. Setelah menginisialisasi npm kita nantinya bisa menginstal npm modules ke applikasi yang kita buat.

Debugging:

  1. Untuk debugging, gunakan module nodemon, sehingga setiap perubahan pada code langsung bisa kita lihat effekt running time nya. Nodemon merestart programm kita setiap kali kita melakukan perubahan. cara menginstall 
    • npm install -g nodemon -g disini berarti global
    • nodemon [your node app] untuk menjalankannya.
  2. Debugging tool dengan menggunakan chrome browser nodemon --inspect-brk [your node app] lalu buka chrome browser dan ketik chrome://inspect
    disini kamu akan melihat app kamu di list di 'Remote Target' section. Setelah debugging window terbuka, kamu bisa mengklick di line number untuk meletakan stop points

19 September 2017

ES6 Features


ES6-string-injection

Di ES6 Ada cara mudah memasukan variable ke dalam String. Kalian cukup menggunakan tanda `Put your String here and add your variable like this ${yourVariable}`



Variable 'let'

Perbedaan utama di variable let adalah pada scope-nya. let syntax memungkinkan kita untuk mengimplementasi local variable dengan mudah.



Arrow Function

Arrow function sangat memudahkan kita menulis code di javascript. Tapi penggunaan arrow function saya sarankan hanya seandainya kamu sudah tau menulis fungsi tanpa menggunakan arrow function. karena penggunaan arrow function akan membingungkan tanpa memahami proses apa yang terjadi di balik itu.



Object destructuring

Kalian bisa membuat variable baru dari objects' properties



Promises

Untuk menghandle Asynchronous call, kita bisa menggunakan Promise methode. Cara ini lebih baik karena bisa meminimalisir kesalahan ketika berkerja dengan asynchronous methods.



26 April 2017

MatLab | Backslash ('\') or Left matrix division

Backslash denotes left matrix division. x=A\b is a solution to A*x=b.

25 March 2017

Off-Topic | Ubuntu | No wifi connection after standby modus

If you're using Ubuntu on Lenovo ThinkPad T430 series, you might have the same problem as me: No internet connection after you've woken up your laptop from standby modus.

I haven't found any better solution yet but this will solve your problem: go to terminal and run this code sudo service network-manager restart please write comments if you have more automated solution for me.

12 March 2017

Java | Client & Server | Simple Socket Programming

To make an application that can communicate with other applications like chat-app or multiplayer games, we need a server that serve data between clients. A Client send data to the server and the server send it to another client. Server and client send data to each other via sockets.
How to create a Server
  • Create a class with a main method
  • Create an instance of ServerSocket. You need to pass any port number as a parameter ServerSocket ss = new ServerSocket(9999);
  • In order to accept an incoming client connection, we have to call the ServerSocket.accept() method. As soon as connection request is made from client, this method will return a socket that created specifically for this client.
  • To send and receive data from client, you can use OutputStreamWriter and BufferedReader
  • The Server
How to create a Client
  • Create a class with a main method
  • Create an instance of Socket class and pass the port number and the private ip address of your server as parameter.  You can use localhost instead of ip for local testing. Socket s = new Socket(ip, port);
  • To send and receive data from client, you can use OutputStreamWriter and BufferedReader
  • The Client
How it works
Run the server. once the accept() method is called, the server will wait for a client to connect. When you run the client, a connection request is made and ServerSocket will then create a socket that is connected to the client's socket until Socket.close() method is called. To make a simple chat application, put a Writer and a Reader in a while loop and use a Scanner to take user input.

10 March 2017

Java | Important Syntax

  • Ternary Operator
  • It is basically a simplified if statement. If the condition is true, the first value will be assigned to the variable. if false, the second value will be assigned.
    The statement is false. So x will have the value of b

Java | try with resources statement

Since Java 1.7 you can declare all resources that can be closed. e.g BufferedReader right after the try statement. With this feature, all resources will be closed and errors will be caught automatically. Before Java 1.7 you'll have to close all resources manually. like this:
managing resources before java 1.7
Since Java 1.7 this is simplified to this:
managing resources after java 1.7

9 March 2017

Java | Important classes

BufferedReader vs Scanner
  • BufferedReader has a bigger buffer (8192 chars) than the one using in scanner (1024 chars). Use BufferedReader if you want to get long String from a stream.
  • BufferedReader is synchronized or thread safe while scanner is not
  • Use scanner if you want to parse a file and use BufferedReader if you want to read line by line
  • To use readLine() method, you have to create BufferedReader object and put a class that extends Reader object as a parameter: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); The parameter of the InputStreamReader is your input source, in this example we get an input from the console. System.in Be sure to put BufferedReader object in try block to manage the resources.
using BufferedReader in try block
Serializable
Let's think about a game. After some hours of playing game, you might want to have a break. You want to save the current state of your game so you can continue later from the same point. When saving a game or an application. You want to save the state of objects that have been created during the runtime of your application. In Java an Object cannot be stored in a file as an Object. It can only be stored if it converted to a stream (of bytes) beforehand. The process of converting is called serialization.

Some reasons for serialization are:
  • An object is created on the heap and the heap is for temporary storage. Only serialized objects can be saved as a file
  • To transmit data or state of an object to different location through the network
To make an Object serializable the class muss implement Serializable interface
make a class serializable
This is how you save an object into a file.
save an object as a file
And to retrieve the saved object.
retrieve the state of an object from a file

JavaFX | Basic Knowledge

The Stage

In JavaFX the The user interface is the 'Stage'. Like in a theater, the stage is where all the events will be presented to the audiences or the users.
To create a JavaFX application on IntelliJ, you simply have to create a new JavaFX class.
Creating JavaFX application
After you created the JavaFX application, you can see, there is a start method to be implemented. For now the curtains of the stage is still closed. You can open the curtains by adding primaryStage.show(); to the start method.
adding show method to open the stage
If you now run the application, you'll see an empty 'stage'. The stage is there, now it is up to you to perform a show

The Scene

Now that you have a stage, you might want to perform a show. To do that, you'll need a scene. In a scene, there are some props or in Java terms, 'nodes'. A node can be a button, text field or just a label. To create a good scene you might want all these nodes to be organized nicely. Some nodes that build one feature, should also be placed side by side so the user will know intuitively what these nodes are about. Nodes is organized in a class called Parent. In Web term, it is similar to div tags. You can organize the nodes vertically using VBox Parent or horizontally using HBox Parent.

Layouts

BorderPane
BorderPane is a layout with five areas: Top, left, center, right and bottom.
GridPane
As the name said, GridPane works with grid system.
use indexes to organize the nodes
use hgap and vgap to control the space between grid
when there is not enough space, the nodes will shrink to fit the window

28 February 2017

Git | Github | Summary and get started

Quick setup

  • Install git, sudo apt-get install git
  • Create Github account
  • In terminal, generate SSH key cd ~/.ssh && ssh-keygen leave passphrase empty, just press enter until the key is created
  • While still in ssh directory, cat id_rsa.pub and copy the entire key
  • Go to your Github setting, SSH and add SSH. paste the key in the key field. Give it a proper name and save
  • Go back to terminal, setup username and email on git git config --global user.name "john" and git config --global user.email "john.doe@gmail.com" Remember the username and email address muss be the same as the ones used for Github account
  • Go back to Github, create a new repository.
  • Now go to the folder of your application. cd /path/of/your/application and run these command
  • git init
  • git add -A
  • git commit -m "any message e.g. 'my first commit'"
  • Add your ssh URL or copy paste from your Github repository page git remote add origin ssh://login@IP/path/to/repository
  • git push -u origin master

27 February 2017

Javascript | Important functions

  • document.querySelctor('.class_name') using query selector you can grab the html tags by its class
  • example of query selector and event listener within a module
    'click' in above example is the type of listener. You can find any kind of listener on this event reference
  • To add an event listener to any key of a keyboard e.g. 'Enter' (13) key, you can do it like this:
  • change keyCode to any code of the keyboard.
    You can find the code of any key of your keyboard from keycode.info

Important concept or features in programming languages.

Ternary operator

Javascript: var result = (condition) ? (value1) : (value2) ; in this code, the 'var result' will have either 'value1' or 'value2' depend on the condition provided.

Javascript | Basic Knowledge

IIFE

IIFE or 'immediately invoked function expression' is basically an anonymous function wrapped in parenthesis.

add function is private and publicTest is a public function
variable x is still exist even though the anonymous function has already returned. This is possible thanks to the power of 'closure'. All variables inside the IIFE are private and the functions inside the return statement are public.
IIFE can also have arguments like this:
Go to browser console and call 'hello' to see the output

Closures

In Javascript you can have nested functions or function inside a function. The inner functions will have access to all variables of the parent function. This feature, combined with IIFE build another Javascript feature called 'closure'.

Modules

Javascript doesn't natively support classes. To implement classes in Javascript, we use modules. To create a module, we combine self-invoking function (IIFE), encapsulation and closures altogether
Three modules in an application. The third module connected the other modules

Callback function

Callback function is basically a function that is passed to another function as a parameter or an argument. Do not attach the ( ) (function brackets) to the callback function, because the function will be called only if the parent function is called. So the calling process is done by the parent function. 
ctrlAddItem is passed as parameter. No function brackets needed.

24 February 2017

How to access your windows documents folder from the ubuntu bash

  1. make sure you are in root. cd ~
  2. type in cd /mnt and ls to list the content
  3. Now you can go to the volume where your data stored using cd path/../
  4. To go to 'Documents' from root, cd /mnt/c/Users/YourUserName/Documents

How to install Ubuntu linux bash on windows 10

As developer, it sometimes easier to use bash to do some process. e.g. it's easier to install Git from the bash and also it's easier to commit a file or create and delete a branch from the command line.

Steps:
  1. Go to start >> settings >>  Update & security
  2. Go to For developers and active the Developer mode radio button. 
  3. Go to Programs and Features >> Turn Windows features on or off
  4. Select the check box on Windows Subsystem for Linux(Beta)
  5. Reboot your computer
  6. To use the bash, go to start, type in "Ubuntu" or "bash"

22 February 2017

Python | Basic Syntax And Rules

Indentation

  • Very important! in Python indentation is relevant! see this examples:
  • Indentation is correct!
    Wrong indentation gives different result

Operators

  • To check if one variable is exist in another variable, use in
  • To check if a variable is equal to a specific value, use is
  • in and is
  • In python, 5 ** 3 means 5 to the power of 3 and it will return 125 as a result
  • In python and most of programing languages, \n means 'new line'. But how if we want to print out a path like this "C:\Arkad\Desktop\notepad"? if you write print("C:\Arkad\Desktop\notepad") you'll get this result:
  • \n means newline
    To avoid this, put 'r' before the quote sign. like this print(r"C:\Arkad\Desktop\notepad")
    put 'r' before the quote sign
  • In Python you can do 'multiplication' operations with strings name = "John" and name * 5 this will return "John John John John John"
  • To create an array or a list, variable = [12 , 15 , 10 ]
  • To add elements to a list, variable + [10 , 9]
  • how to add items to a list
  • In Python, colon operator like this variable[0:2] will return the first and second elements of the list. it means index '2' is not included. This is different to e.g. Matlab where an array is started with number '1' and the colon operator include the number coded

String format

  • The number inside the curly brackets refers the index of the arguments inside the round brackets. '0' means the first argument etc.
  • '{2}' means 'third argument'

Looping

  • For loop in Python can be very flexible. Look at this code:

Ruby on Rails | Production

Add Admin role in Production

  • Go to heroku console heroku run rails console grab the user you want to set to admin. user = User.find(id) or user = User.first and use this command to toggle the admin from false to true. user.toggle!(:admin)
  • Rails console at heroku

21 February 2017

MatLab | Basic Knowledge

Arrays and Metrices:

  • Variable for one dimensional vector should be start with lowercase.
  • Variable for two dimensional vector (matrix) should be start with Uppercase.
  • Scalars is  one by one matrices. 
  • Not like java or ruby, the first element of an array in Matlab is indexed by number 1
  • Let say x is a 3x3 matrix. X(2,2) return the element from second row and second column. If you want to change the value, simply assign a new value. X(2,2) = 5
  • If a variable XYZ doesn't exist and you type in a command XYZ(2,2) = 3 Matlab will give you 2x2 matrix with XYZ(2,2) equals to 3 and rest elements of 0
  • X(2,[1 3]) gives you the 1st and the 3rd elements of the second row of a matrix.
  • X([1 2],2) gives you the 1st and the 2nd elements of the second column of a matrix.
  • For matrix multiplication the inner dimension muss be equal. 5x3 matrix * 3x4 matrix works just fine. but 5x3 matrix * 2x4 matrix gives you an error.
  • Use randi( maxNumber , numberOfRow , numberOfColumn) to create a random matrix of integers
  • let say X is a matrix. X^2 means X*X or matrix multiplication. and X.^2 means to square each element of X. And X.^Y means to tell Matlab to exponentiate each element of X to the power of element of Y of the same index. 
  • Use find(A); to find all non zero elements of matrix A. The output of this function is a vector containing linear indices of each non zero elements in matrix A
  • Elements with index: 1, 3, 5 and 7 are not zero

Operators:  

  • Colon ':' operator: x = 1 : 3 : 7 means we tell Matlab to create row vector start from 1 increment it by 3 till its maximum of 7. it will give you a result x = 1 4 7
  • Colon operator is very useful to create an array of odd or even numbers 1:2:7 will return an array of odd numbers[1, 3, 5, 7]
  • Colon operator can also give you an array in a decreasing order. 10:-3:1 will return [10, 7, 4, 1]
  • ints = 1 : 10 means give me an array of numbers from one to ten
  • A * B or mtimes(A,B)means matrix A times matrix B. A .* B or times(A,B)
  • More operator can be found in Matlab Operators
  • size(variable) gives you the size of a matrix. e.g. x = [3 2 4 ; 2 5 6] and size(x) gives you ans = 2 3 matrix of 2 rows and 3 columns 
  • Any scalar for. e.g. x = 2 and size(x) gives you ans = 1 1 since in Matlab scalar is one by one matrix.
  • Some operators can also be written as a function: plus(1,2) means 1+2 ans = 3and colon(1,7) gives you [1, 2, 3, 4, 5, 6, 7]

Function handles

Function handles are Variables that allow you to invoke a function indirectly. Using function handles you can pass a function as a parameter of another function. For example I have a function f(x)=3x^4 - 2x^2
And we want to pass this function to another function like this:
Now if you try to call the function using diffQuotF(f, x0, h) you'll get an error message.
The right way to pass the ' f ' function as a parameter is by using the @ (at) sign before the ' f '. like this:

Git | Github | Basic Knowledge

  • If we work on feature of an application, we have to be careful that changes that have been made aren't going to break the application. In Git, we have a master branch where the application is stored in production and we can also have a feature branch to work on a feature in development. Any changes made in this branch will not affect our master branch. this allows many developers to work on different features of an application without touching the application in production. 
  • to create a new branch type in this command in the application directory: git checkout -b branchName
  • To check in what branch you are currently in and to see all existing branches in git: git branch (your current location will be marked with asterisk)
  • To go back to master branch: git checkout master
  • When creating new branch, keep in mind that you cannot "git push" from your new branch. You'll have first to create a new branch in your github. You can use this one command line to set up a new branch and pushing all at once: git push --set-upstream origin yourNewBranch
  • If you're using Rubymine and you want to merge your branches. I recommend to use merging function from Rubymine interface, not from terminal. I often have merging issues wenn merging from terminal. 
  • Merging is done from the master-branch otherwise changes wont be merge to master and you'll get a message "branch is already up to date.

Useful Command Line

  • To delete a branch (if you're in master branch): git branch - d branchName
  • To delete a folder in git but not in local git rm -r --cached myFolder

Ruby on Rails | Data Base

Database

  • IDs columns are mostly generated by rails.
  • To create a single migration use this command: rails generate migration create_tableName >> e.g. rails generate migration create_articles
  • after generating migration, you'll need to add column to your table. By adding it to your migration file. When you're finished type in: rake db:migrate
  • To create table and everything related to it, you can simply type in this command line: rails generate scaffold Tablename firstColumn:dataTyp secondColumn:dataTyp >> e.g. rails generate scafold User username:string email:string
  • A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
  • To migrate your database type in: rake db: migrate
  • Migrations are a convenient way to alter your database schema over time in a consistent and easy way. They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent.
  • In 'rails console' you can change the data of your database using ruby code. For example, in the 'users' table you can grab any user by 'user_id' using User.find(userID) or if you want to toggle any Boolean information in your database, you can use this code: user = User.find(1) and user.toggle!(:admin) this code will change admin status of user 1 to true or false. change User and :admin to your need

Validation

  • Validations are added in model class. 
  • Example of validations of presence and length: validates :username, presence: true, length:{minimum: 3, maximum: 25}
  • Example of validations of uniqueness: validates :email, uniqueness:{case_sensitive:false}
  • If you want that all emails are to be formatted to lowercase in your database, simply add before_save {self.email = email.downcase} to your User model.
  • more example: http://guides.rubyonrails.org/active_record_validations.html

Association

  • To create foreign key association when creating scaffold, type in: rails generate scaffold TableName firstColumn:dataType secondColumn:dataType tableTobeAssociated:references >> e.g. rails generate scaffold Comment description:text user:references 
  • Now we know that association has been made between users and comments, we might want to explicit some details of association. for example we want to tell our database that a user can have many comments, we have to add this line to the User model: has_many :comments
  • If you want to associate two tables manually, you will have to make some changes to the model of each table. In the User model, we have to add has_many :articles ; and in the Article model, we have to add belongs_to :user
  • This will store the userID in your table whenever a comment is made.

 

Useful command line

  • To go to rails console for testing your database : rails console
  • To exit the console: exit
  • To see the existing routes: rake routes
  • To destroy scaffold in case you made mistakes: rails destroy scaffold TableName
  • You have to be in your app directory before using all this command.

Ruby on Rails | Secure password

To store a secure password we have do the following:
  • add gem 'bcrypt' in application gemfile
  • add has_secure_password method in model (user.rb)
  • add password_digest of type string in the table attribute (users)

Ruby on Rails | Gemfile

Useful command line

  • bundle install --without production to install the gem in development environment.

Ruby on Rails | Routes

The Rails router recognizes URLs and dispatches them to a controller's action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.

-Rails Guide-
If you type in www.example.com in your browser, this request will be sended to your webserver. Your router (routes.rb) recognize the URLs as a root, and dispatches it to whatever Controller's action you've specified in your routes.rb file. root 'pages#home' will dispatch your request to PagesController and call the home action.

If you have a form in your page, you will need to have a route so whenever you pressed the submit button, it will understand what action to perform.

To add routes you can add this code to your routes.rb file: resources :pluralObjectName e.g. resources :photos this will create 7 different routes in your application. You can also create any route manually. for a form for example, you can add post 'users', to:users#create" with this whenever you press submit, it will call the 'create' action in the UsersController and eventually redirect user to the page you've specified in the UsersController

Ruby on Rails | Partials

If you have exactly or almost exactly the same code in different places, you can make one generic code of them and use it as a template using partials.

Examples

  • In views folder, you might have the same code for a form in  new.html.erb and edit.html.erb. You can create another file named _form.html.erb and put all the same lines of code in it. In the original place, you can replace the code with <%= render 'file_path' %> please keep in mind that the path should begin with folder name where the file is located.
  • In your partial template, you can also declare variables and you can assign the value of the variable in the target page like this <%= render 'file_path' , variableName: value %>
  • Now and then you will have the situation where the codes are exactly the same except one or two lines. Fortunately rails give us method to handle this. e.g. you want to have different label for a button; on the new page you want it to be labeled "create" and on the edit page you want it to be labeled "update". Simply modify your code into this: <%= f.submit(@user.new_record? ? "sign up" : "update your account" %>

Ruby on Rails | Action Controllers

Things to know

  • Controller are connected to the view by the actions defined in it. If you declare a variable within the action, this variable will also be accessible in the views template file. e.g. if you define a @user in users_controller, @user will also be accessible in whatever template you created in users sub-folder of views.

Ruby on Rails | Application Helper

All methods used in views muss be defined in the application_helper.rb file. Once you defined a method in application helper, it will be available in all views pages.

Ruby on Rails | Pagination

As time went by, the number of article in your blog has increased rapidly. Your articles page become very long. To solve this we can use pagination.

Steps:

  1. In your gemfile, add gem 'will_paginate','version' and gem 'bootstrap-will_paginate', 'version' change the version to current version of the gem. 
  2. bundle install --without production --If production group exists-- to install the gem. 
  3. In articles_controller, at index action, change the variable value to Article.paginate(page: params[:page], per_page: 10) If you want to show more than 10 articles, simply change the number. 
  4. Add <%= will_paginate %> wherever you want to place the pagination.

Ruby on Rails | Sessions (login logout)

How to create session in Rails

  • Create route: get 'login', to: 'sessions#new'
  • Create route: post 'login', to: 'sessions#create'
  • Create route: delete 'logout', to: 'sessions#destroy'
  • Create sessions sub folder in controllers directory, and create new file, sessions_controller.rb
  • Create new, create and destroy actions.
  • In views, create new.html.erb
  • In application_controller.rb, create current_user, logged_in and require_user actions

Ruby on Rails | Basic knowledge

Things you should know in Ruby on Rails:

  • Actions that you created in application controller will be available in all your controller but they are not available to views by default. 
  • To make those actions to be available to views, add this code in the same file: helper_method :action1, :action2, and so on. 
  • In Ruby, "foo".equal? "foo" will return false and :foo.equal? :foo will return true It works that way because strings in Ruby are mutable. Unlike strings, symbols(:foo) are immutable.
  • params[:foo] in @user = User.find(params[:id]) means to tell rails to get the ':foo' or ':id' from the URL of the page that user requested
  • In this case, params[:id] is 1

Ruby on Rails | Syntax

Important syntax you have to know:

  • <% code %> to embed Ruby code in your HTML file. 
  • <%= code %> to generate HTML code with ruby methods. 
  • !!code to convert the code into Boolean statement.  
  • Local variable will be declared as variable and instance variable will be declared as @variable
  • Local variable only exists within its scope. Declaring variables in the controller as instance variables @variable makes them available to your view. 
  • a ||= b This operator means if 'a' is undefined then assign it the value of 'b', otherwise leave it alone.
  • @current_user ||= User.find(2) this means if @current_user is undefined, assign the value of user with user_id 2 to the @current_user otherwise perform nothing.
Please check this link for more Ruby Operators

Virtual Box | Windows Host & Ubuntu Guest | Shared Folder

Follows this steps to create a shared folder between windows host and ubuntu guest

  • Create shared folder at Vbox -> settings -> Shared Folders -> plus button -> specify path 
  • Go to your ubuntu guest create new folder somewhere: sudo mkdir newFolder
  • Mount your shared folder to the new folder you just created sudo mount -t vboxsf sharedFolder newFolder change shared folder with the folder you specified in Virtual box settings

Ruby on Rails | Typing Convention

Working with databases

  • Model class name is singular, starts with uppercase. e.g. class Article < ActiveRecord::Base
  • Model file name is singular, all lowercase. e.g. article.rb
  • Table name is plural of model name, all lowercase e.g. articles

Working with Buttons and Controllers

  • Controller class name is plural and written in CamelCase e.g. class ArticlesController
  • Controller file name is also plural but separated by "_" e.g articles_controller.rb

Ruby on Rails | Bootstrapping

What you should know about using Bootstrap alongside of RoR

    • Understanding Bootstraps 12 columns grid system.
    • Combine <blockquote> and <footer>  to get awesome quote effects. 
    • With class="row" you'll get a column without padding
    • When designing responsive website, keep in mind, Bootstrap will use the smallest break point first. for eg. class="col-lg-6 col-xs-4" On ipads or tablets (medium size) col-xs-4 will be used.
    • All columns will be placed from left to right. If you want to force them to be placed more right than it should be, you can use offset attribute. class="col-lg-3 col-lg-offset-6" This will create an element that take 3 columns and place it six column from the left or from its original place .
    • Class="container" will centered your container, while class="container-fluid" will stretch the your container to cover the whole screen.    
    • To apply Bootsraps forms to rails model backed form, you'll need to modify your ruby code into something like this: <%= form_for(@variableName, :html => {class= "BootstrapFormElement", role: "form"}) do |f| %>