Angular Flashcards
is a container for a group of related components. Every Angular app has at least one of these called App module
Module
are the main building block for Angular applications. Each one of these consists of: An HTML template that declares what renders on the page. A Typescript class that defines behavior. A CSS selector that defines how the (blank) is used in a template.
Components
A blank is one of the properties of the object that we use along with the component configuration. A blank is used to identify each component uniquely into the component tree, and it also defines how the current component is represented in the HTML DOM
Selector
A blank is a blueprint for creating an object, we call that created object an instance of a class, or a class instance or just instance for short. We instantiate a blank by using the new keyword and when that happens JavaScript calls the constructor function.
Class
Blank in Angular is put into use to inject dependencies into the component class. It creates a new instance of the class when the compiler calls ‘new MyClass ()’. While calling ‘new MyClass()’, it is vital that the exact match of the parameter passes the Angular component blank of the class.
Constructor
To use ngOnInit in Angular, it is required to import into the component class in this way – import {Component, OnInit} from ‘@angular/core’. Though implementing ngOnInit for every component is not essential, it is a good practice that further heads towards the smooth functioning of the platform. Angular ngOnInit is created by Angular itself. Angular also renders and checks the changes in its data bounded properties. It is interesting to note that Angular destroys the component before removing it from DOM. ngOnInit in Angular can be hooked to components and directives. Defining the ngOnInit Angular in the class helps Angular runtime to know that is the right time to call the method. The major benefit of this approach is that it adds specific initialization logic near the class lifecycle.
ngOnInit
In Angular, a blank is a chunk of HTML. Use special syntax within a template to build on many of Angular’s features.
Template
Dependencies are services or objects that a class needs to perform its function. Dependency injection, or DI, is a design pattern in which a class requests dependencies from external sources rather than creating them.
Angular’s DI framework provides dependencies to a class upon instantiation. You can use Angular DI to increase flexibility and modularity in your applications.
Dependency injection in Angular
They are instructions in the DOM. They are classes that add additional behavior to elements in your Angular applications. With Angular’s built-in directives, you can manage forms, lists, styles, and what users see.
Directives
Components—directives with a template. This type of directive is the most common directive type.
Attribute directives—directives that change the appearance or behavior of an element, component, or another directive.
Structural directives—directives that change the DOM layout by adding and removing DOM elements.
The different types of Angular directives are as follows:
Decorators are functions that are invoked with a prefixed @ symbol, and immediately followed by a class , parameter, method or property. The decorator function is supplied information about the class , parameter or method, and the decorator function returns something in its place, or manipulates its target in some way.
Decorators
Class decorators, e.g. @Component and @NgModule.
Property decorators for properties inside classes, e.g. @Input and @Output.
Method decorators for methods inside classes, e.g. @HostListener.
Parameter decorators for parameters inside class constructors, e.g. @Inject.
What are types of decorators in Angular?
There are four main types:
Property binding in Angular helps you set values for properties of HTML elements or directives. Use property binding to do things such as toggle button functionality, set paths programmatically, and share values between components.
Property binding
Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches.
Event binding
Is like a reserved variable name that you can use in the template when using event binding. It is the data emitted with said event. It gives us access to event data it allows you to fetch event data. Allows you to grab any data an event passes to us
($event)
It will trigger on the input event and update the value of the server name in our component automatically.
It will also update the value of the input element if we change the value of server name somewhere else
[(@ngModel)]
What are the four form of data binding
Event Binding, String Interpolation, Property Binding, and Two Way Binding.
When building your applications and creating logic, there are times when you want to make comparisons between two or more things. They can be abstract things; they can be items in a list or array or even an object. Angular provides directives to handle these situations called conditionals. So, there is ngIf for times when you want to check for a true or false value, and there is ngFor mostly for a list of items either in an object or an array.
Conditionals
is an Angular directive from the router library that is used to insert the component matched by routes to be displayed on the screen.
Router-Outlet
is a directive which binds input, select and textarea, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during validations in a form. We can use blank with: input. text.
ngModel
We’ll be learning about the @Input() decorator. … Using the @Input() decorator we can instruct the Angular framework that a property in our directive’s class is an input property, and as such, the value of that property can be set via an input binding on the host element.
What is input directive in Angular?
Input data into a Directive
The child component uses the @Output() property to raise an event to notify the parent of the change. To raise an event, an @Output() must have the type of blank , which is a class in @angular/core that you use to emit custom events.
What is the use of EventEmitter in angular?
Getting the input at the point and time that I click the button. You use blank
A blank can be placed on any html element. You can only use a local reference in your template/ or html page
Local Reference
Getting access to local reference or any element directly from our typescript code. This works before you call a method.
@Viewchild
Use blank to quickly execute reusable code in multiple places without having to set up.
ng-content
All the basic types e.g. int, boolean, char, short, float, long and double are known as primitive types. … The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value.
What is the difference between primitive and reference type?
An blank is a pattern that listens to a named event, fires a callback, then emits that event with a value. Sometimes this is referred to as a “pub/sub” model, or listener. It’s referring to the same thing
Event Emitter
Input is used to receive data in whereas Output is used to send data out. Output sends data out by exposing event producers, usually EventEmitter objects. by the way, I will produce and send data out via the onChange property.
A common pattern in Angular is sharing data between a parent component and one or more child components. … @Input() lets a parent component update data in the child component. Conversely, @Output() lets the child send data to a parent component.
The difference between @input and @output angular
The square brackets that are used with ngClass or some directive signify that we are binding to some property on said directive or ngClass
Little reminder about how square brackets indicate property binding when used with directives
There are three kinds of directives in Angular: Components—directives with a template. Structural directives—change the DOM layout by adding and removing DOM elements. Attribute directives—change the appearance or behavior of an element, component, or another directive
What is attribute directive What are the types?
Directives go in our templates so we can attach them to our elements
Yup
blank is a life cycle hook called by Angular to indicate that Angular is done creating the component. Implement this interface to execute custom initialization logic after your directive’s data-bound properties have been initialized.
NgOnInit
The constructor() should only be used to initialize class members but shouldn’t do actual “work”. So we should use constructor() to set up Dependency Injection, Initialization of class fields, etc. ngOnInit() is a better place to write “actual work code” that we need to execute as soon as the class is instantiated.
Why we use ngOnInit instead of constructor?
The new operator instantiates a class by allocating memory for a new object. Note: The phrase “instantiating a class” means the same thing as “creating an object”; you can think of the two as being synonymous. When you create an object, you are creating an instance of a class, therefore “instantiating” a class.
What does it mean to instantiate an object?
Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.
Observables
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of state changes. This pattern is similar (but not identical) to the publish/subscribe design pattern.
Observables Part 2
Means the execution of a program or function.
Invocation
1) In object-oriented programming, the state of an object is the combination of the original values in the object plus any modifications made to them. (2) The current or last-known status, or condition, of a process, transaction or setting. “Maintaining state” or “managing state” means keeping track of the process.
State of an object
The addNewItem() function uses the @Output(), newItemEvent, to raise an event with the value the user types into the .
export class ItemOutputComponent {
@Output() newItemEvent = new EventEmitter();
addNewItem(value: string) {
this.newItemEvent.emit(value);
}
}
In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one. In asynchronous operations, on the other hand, you can move to another task before the previous one finishes.
Synchronous & Asynchronous
Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change (Wikipedia). RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.
What is the use of RxJS in Angular?
In this case, @Input() decorates the property item, which has a type of string, however, @Input() properties can have any type, such as number, string, boolean, or object. The value for item comes from the parent component.
import { Component, Input } from ‘@angular/core’; // First, import Input
export class ItemDetailComponent {
@Input() item = ‘’; // decorate the property with @Input()
}
test() are methods on a regular expression object. . match() is a method on a string and takes a regex object as an argument. . test() returns a boolean if there’s a match or not
test() and match in Regex
Reactive forms provide direct, explicit access to the underlying forms object model. Compared to template-driven forms, they are more robust: they’re more scalable, reusable, and testable. If forms are a key part of your application, or you’re already using reactive patterns for building your application, use reactive forms.
Reactive forms
Template-driven forms rely on directives in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an app, such as an email list signup form. They’re straightforward to add to an app, but they don’t scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.
Template-driven
Common form foundation classes
Both reactive and template-driven forms are built on the following base classes.
FormControl tracks the value and validation status of an individual form control.
FormGroup tracks the same values and status for a collection of form controls.
FormArray tracks the same values and status for an array of form controls.
ControlValueAccessor creates a bridge between Angular FormControl instances and built-in DOM elements.
Common form foundation classes
In Angular, form controls are classes that can hold both the data values and the validation information of any form element. Every form input you have in a reactive form should be bound by a form control. These are the basic units that make up reactive forms
Form Control
FormControl is a class in angular that allow us to manipulate every input field in a form so you can create an instance of the control class. with the control class you can check the value, touched, untouched, dirty, pristine, valid, and errors. These are property’s of form control
More On FormControl
FormGroup is a class that represents a group of controls in a form. Each form is essentially a control group because it contains a least on control. You can use the from control built in properties with FormGroup
FormGroup
pristine: Data entry has not been touched.
dirty: (Input field has been interacted with).
touched: (Input field has received focus).
valid: (Data entry has passed validation)
invalid: (Data entry has not passed validation)
errors: Where data entry have not satisfied the rule
Properties of FormControl and these can be used with FormGroup
Place this code in the html file and where you want to test it —> #emailTest=”ngModel” (change)=”log(emailTest)”
The second part goes in the ts file under export class.
Place this code log(x) { console.log(x); } and that is it!
Testing validation in ionic/Angular
Angular router can interpret a browser URL as an instruction to navigate to a client-generated view. It can pass optional parameters along to the supporting view component that help it decide what specific content to present.
What is the use of router in Angular?
It’s a method that comes from rxjs library which Angular is using internally.
If you can imagine yourself subscribing to a newsletter, every time there is a new newsletter, they will send it to your home (the method inside subscribe gets called).
That’s what happens when you subscribing to a source of magazines ( which is called an Observable in rxjs library)
All the AJAX calls in Angular are using rxjs internally and in order to use any of them, you’ve got to use the method name, e.g get, and then call subscribe on it, because get returns and Observable.
Also, when writing this code , Angular is using Observables internally and subscribes you to that source of event, which in this case is a click event.
Back to our analogy of Observables and newsletter stores, after you’ve subscribed, as soon as and as long as there is a new magazine, they’ll send it to you unless you go and unsubscribe from them for which you have to remember the subscription number or id, which in rxjs case it would be like :
let subscription = magazineStore.getMagazines().subscribe(
(newMagazine)=>{
console.log('newMagazine',newMagazine); }); And when you don't want to get the magazines anymore:
subscription.unsubscribe();
Also, the same goes for
this.route.paramMap
which is returning an Observable and then you’re subscribing to it.
What is .subscribe in Angular?
AJAX calls are one method to load personalized content separately from the rest of the HTML document, which allows for the full HTML document to be cached, improving back end load time
What is an ajax call?
is a string that refers to a resource.
The most common are URLs, which identify the resource by giving its location on the Web. URNs, by contrast, refer to a resource by a name, in a given namespace, such as the ISBN of a book.
A URI (Uniform Resource Identifier)
What are escape sequences?
Character combinations consisting of a backslash () followed by a letter or by a combination of digits are called “escape sequences.” To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences.
What are escape sequences?
encodeURIComponent()
The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two “surrogate” characters).
encodeURIComponent()
(keyup) is an Angular event binding to respond to any DOM event. It is a synchronous event that is triggered as the user is interacting with the text-based input controls. When a user presses and releases a key, the (keyup) event occurs.
(keyup)
GET is used for viewing something, without changing it, while POST is used for changing something. For example, a search page should use GET to get data while a form that changes your password should use POST . Essentially GET is used to retrieve remote data, and POST is used to insert/update remote data
GET and POST
A RESTful API is an architectural style for an application program interface (API) that uses HTTP requests to access and use data. That data can be used to GET, PUT, POST and DELETE data types, which refers to the reading, updating, creating and deleting of operations concerning resources.
What is REST API and why it is used?
For example, a REST API would use a GET request to retrieve a record, a POST request to create one, a PUT request to update a record, and a DELETE request to delete one. All HTTP methods can be used in API calls. A well-designed REST API is similar to a website running in a web browser with built-in HTTP functionality.
What is REST API example?
Headers in a HTTP request or response is the additional information that is transferred to the user or the server. In postman, the headers can be seen in the Headers tab
Headers
What is header and body in Postman?
Image result for what are headers in postman
The Body tab in Postman allows you to specify the data you need to send with a request. … If you use raw mode for your body data, Postman will set a header based on the type you select (e.g. text, json).
What is header and body in Postman?
Are parameters variables in JavaScript?
Functions are obviously very important in Javascript. When talking about functions, the terms parameters and arguments are often interchangeably used as if it were one and the same thing but there is a very subtle difference. Parameters are variables listed as a part of the function definition
Are parameters variables in JavaScript?
Hot Reload
Hot reload just displays the code changes according to new code changes without restarting the app from the start and its effects only on the changed code or change will only apply to a specific component.
Hot Reload
A change listener is similar to a property change listener. A change listener is registered on an object — typically a component, but it could be another object, like a model — and the listener is notified when the object has changed.
Change listener
NgModel
DIRECTIVE
Creates a FormControl instance from a domain model and binds it to a form control element.
NgModel
DIRECTIVE
Element: blur event
The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not.
The opposite of blur is focus.
Element: blur event
The (change)=”changeFn($)” will fire after the value bound to [(ngModel)] has changed
The (ngModelChange)=”modelChangeFn($event)” will fire before the value bound to [(ngModel)] has changed.
What about when the event fires and the model value is set?
npm install br-mask –save -E
Auto format Phone numbers
IsLoadingService is a simple angular service for tracking whether your app, or parts of it, are loading. By subscribing to its isLoading$() method, you can easily know when to display loading indicators.
What is isLoading in angular?
Definition and Usage. The ng-submit directive specifies a function to run when the form is submitted. If the form does not have an action ng-submit will prevent the form from being submitted.
ng-submit directive
The name attribute specifies a name for an HTML element.
This name attribute can be used to reference the element in a JavaScript.
For a element, the name attribute is used as a reference when the data is submitted.
For an element, the name attribute can be used to target a form submission.
For a element, the name attribute is associated with the <img></img>’s usemap attribute and creates a relationship between the image and the map.
For a element, the name attribute specifies a name for the information/value of the content attribute.
For a element, the name attribute is used together with the value attribute to specify parameters for the plugin specified with the tag.
HTML name Attribute
The constructor() should only be used to initialize class members but shouldn’t do actual “work”. So we should use constructor() to setup Dependency Injection, Initialization of class fields etc. ngOnInit() is a better place to write “actual work code” that we need to execute as soon as the class is instantiated.
Why we use ngOnInit instead of constructor?
To instantiate is to create an object from a class using the new keyword. … A class contains the name, variables and the methods used. The variables and methods belonging to a class are called member variables and member methods. To reference the desired member variable or method of the instance use the dot operator.
To instantiate is to create…….
Since git rebase command essentially re-writes git history, it should never be used on a branch which is shared with another developer (Unless both developers are kind of git experts). Or as its also said, never use the rebasing for public branches.
The Golden Rule of Git Rebase
- Public: All the properties and methods could be accessed everywhere if they are declared as public. 2. Private: The private declared properties and methods can be accessed only within the class definition itself.
What is public and private in angular?
I have tried (ionInput) but did not fired any event in it . then I tried (input) then it worked for me. So make sure you are correct at it or may be i am missing at some point.
Now difference between (input) & (ionChange)
(input) : This event fires when user tries to enter value in input field, it will fire even when user copy same value and paste it in field. because it does not mater which value is get entered in it.
(ionChange): This event fires only when user change value of input field. if user copy and paste same value it will not get fired.but if user enters different value then it will fire. because it matters values of input field.
The difference between (input) & (ionChange)
I guess you misunderstood what a type assertion does. It’s not something that compiler ensures, it’s a kind of “waiver” you give the compiler saying “I hereby renounce the right to have this type checked, I guarantee that it will be X at run-time and I’m responsible for consequences if it is not”.
By using the ! assertion you’re basically telling the compiler “shut up, I know better, this never gonna be null”. The compiler has no option but to agree with you, but if you don’t keep your promise (which you don’t), a run time fault is imminent.
Obviously, a type assertion is almost never a good idea. Finally, the whole point of Typescript is to have your types statically checked. Think twice before putting ! or as here and there.
The non-null assertion operator
The non-null assertion operator is a concise way of avoiding unnecessary null and undefined checks in our code. We should only use this when we definitely know the variable or expression can’t be null or undefined
The non-null assertion operator part two
To use a service you have to pass it into the constructor as a provider
Yup
A provider is an object declared to Angular so that it can be injected in the constructor of your components, directives and other classes instantiated by Angular. … A service is a particular type of provider that is declared with its class name, as you can see in the Angular tutorial.
Providers are classes that create and manage service objects the first time that Angular needs to resolve a dependency. Providers is used to register the classes to an angular module as a service. And then, this service classes can be used by other components during the itself creation phase in the module.
A provider
The HTTP client in Angular returns an observable
Correct
That means it will subscribe itself to the observable of interest (which is getTasks() in your case) and wait until it is successful and then execute the first passed callback function which in your case is: tasks => { console. log(tasks); }
Subscribe
The .subscribe() function is similar to the Promise.then(), .catch() and .finally() methods in jQuery, but instead of dealing with promises it deals with Observables.
Subscribe part 2
A collection of matrix and query URL parameters.
Correct
Declarations are for components and imports are for Modules
Also Correct
In the context of web and network programming:
When we call a function the function may return a value. When we call a function and the function is supposed to send those results to another function we will not user return anymore. Instead we use emit. We expect the function to emit the results to another function by our call.
A function can return results and emit events.
Emit
export interface Task {
}
You use the export, so that you can bring the data into other files in the app
export class TasksComponent implements OnInit {
tasks: Task[] = TASKS;
Task[] is your interface and TASKS is the actual data
You can use this in your task component to loop over the mock data array and output whatever we want for each particular set of data
let task of tasks is for looping over the mock data file
you use the *ngFor directive
Territory mapping
Sales territory mapping is the process of defining the area, sales, and revenue that your reps are responsible for targeting. If done properly, it can help you reach the right customers, hit revenue goals, and promote growth. Traditionally, sales territory mapping is based on a single, simple factor: geography.
Territory mapping
A source layer is an individual layer of data within a vector source. A vector source can have multiple source layers. A source layer differs from a style layer, which is used to add styling rules to a specific subset of data in a map style.
What is source layer in Mapbox?
This is a custom mode for @mapbox/mapbox-gl-draw that displays data stored in Draw but does not let the user interact with it. This mode used to be one of the core modes prior to the v1. 0.0 release of Mapbox Draw.
Mapbox Draw Static Mode
Simple loading modal to block users from preforming actions on a page while gracefully indicating the state of a background process.
Loading Modal
Toast are the message box or you can say notification box which you can use to show messages/notification on top of the view. Toast displays a message below in the header at the top of the view. In this blog, we are going to learn about how to show toast in salesforce Lightning record page by using “force:showToast”
ShowToast
With Feature State, you can update the “state” of a feature at run-time, allowing control over the style of the individual feature without the map rendering engine (Mapbox GL) having to re-parse the underlying geometry and data
Feature State
showArea
It shows exactly where you are at on the map
A handler is a routine/function/method which is specialized in a certain type of data or focused on certain special tasks. Examples: Event handler - Receives and digests events and signals from the surrounding system (e.g. OS or GUI). Memory handler - Performs certain special tasks on memory
What is a handler function?
TypeScript infers the type of the e parameter in handleChange to be any . So, no type checking will occur when e is referenced in the handler implementation. … So, the type is ChangeEvent .
What is type of e in TypeScript?
The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.
As noted below, calling preventDefault() for a non-cancelable event, such as one dispatched via EventTarget.dispatchEvent(), without specifying cancelable: true has no effect.
Event.preventDefault()
Ruby on Rails
Ruby on Rails
To get Rails saying “Hello”, you need to create at minimum a route, a controller with an action, and a view. A route maps a request to a controller action. A controller action performs the necessary work to handle the request, and prepares any data for the view. A view displays data in a desired format.
What do you need to say hello in ruby?
In terms of implementation: Routes are rules written in a Ruby DSL (Domain-Specific Language). Controllers are Ruby classes, and their public methods are actions. And views are templates, usually written in a mixture of HTML and Ruby.
What are the terms of implementation in ruby?
A model is a Ruby class that is used to represent data. Additionally, models can interact with the application’s database through a feature of Rails called Active Record.
To define a model, we will use the model generator:
Generating a Model
Migrations are used to alter the structure of an application’s database. In Rails applications, migrations are written in Ruby so that they can be database-agnostic.
Let’s take a look at the contents of our new migration file:
5.2 Database Migrations
To play with our model a bit, we’re going to use a feature of Rails called the console. The console is an interactive coding environment just like irb, but it also automatically loads Rails and our application code.
5.3 Using a Model to Interact with the Database
A Ruby module is an important part of the Ruby programming language. It’s a major object-oriented feature of the language and supports multiple inheritance indirectly. A module is a container for classes, methods, constants, or even other modules.
Is Ruby Object oriented
The new route is another get route, but it has something extra in its path: :id. This designates a route parameter. A route parameter captures a segment of the request’s path, and puts that value into the params Hash, which is accessible by the controller action. For example, when handling a request like GET http://localhost:3000/articles/1, 1 would be captured as the value for :id, which would then be accessible as params[:id] in the show action of ArticlesController.
A route parameter
So far, we’ve covered the “R” (Read) of CRUD. We will eventually cover the “C” (Create), “U” (Update), and “D” (Delete). As you might have guessed, we will do so by adding new routes, controller actions, and views. Whenever we have such a combination of routes, controller actions, and views that work together to perform CRUD operations on an entity, we call that entity a resource. For example, in our application, we would say an article is a resource.
Rails provides a routes method named resources that maps all of the conventional routes for a collection of resources, such as articles. So before we proceed to the “C”, “U”, and “D” sections, let’s replace the two get routes in config/routes.rb with resources:
6.2 Resourceful Routing
The resources method also sets up URL and path helper methods that we can use to keep our code from depending on a specific route configuration. The values in the “Prefix” column above plus a suffix of _url or _path form the names of these helpers. For example, the article_path helper returns “/articles/#{article.id}” when given an article. We can use it to tidy up our links in app/views/articles/index.html.erb:
How does the resources method set up URL and path helper methods
However, we will take this one step further by using the link_to helper. The link_to helper renders a link with its first argument as the link’s text and its second argument as the link’s destination. If we pass a model object as the second argument, link_to will call the appropriate path helper to convert the object to a path. For example, if we pass an article, link_to will call article_path. So app/views/articles/index.html.erb becomes:
What does line_to do?
Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller
What is resources in Ruby on Rails?
Every web-page needs a controller and a route in Ruby
True
erb is imbedded ruby which is allowed on all html pages
True or
link_to example: home_about_path. Home = controller,
about = web page, and path = path
Also as a side note you can type in rails routes and looks under the prefix verb and see what your links would be named like home_about GET
root GET
What is a link_to composed of?
When you create a migration you need to push that migration, rails generate devise user will create the migration and the rails db: migrate will push the migration.
How do you create and push a migration in ruby using the devise Gem
or if you want to output it
Imbedded Ruby
Params in Ruby are form fields
What are Params in Ruby
Rails Associations
N/A
MVC = Model is the Database, the View is the webpages and the Controller is the brains
MVC overview
Instance variable in Ruby
What’s an instance variable? In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. Example: @fruit. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.
In a database, a record (sometimes called a row) is a group of fields within a table that are relevant to a specific entity. For example, in a table called customer contact information, a row would likely contain fields such as: ID number, name, street address, city, telephone number and so on.
What is a record in databasing??
Interactive Ruby Shell is a REPL for programming in the object-oriented scripting language Ruby. The abbreviation irb is a portmanteau of the word “interactive” and the filename extension for Ruby files, “.rb”
What is IRB in Ruby??
A block is the same thing as a method, but it does not belong to an object. Blocks are called closures in other programming languages. There are some important points about Blocks in Ruby: Block can accept arguments and returns a value. … A block is always invoked with a function or can say passed to a method call
A block in Ruby
Every Test Ever 1. Sets stuff up, 2. Invokes a thing, 3. Verifies behavior
Tests also
Arrange, Act , and Assert
or
Given, When, Then
Every Test Ever
It’s not a Ruby keyword, it’s part of the Rspec framework.
it contains the code examples that illustrate the facet of behavior being defined. It is comprised of two main parts: the description string and the code example, in the do/end block
After the it:
write a description or a name for the test
and after that within the expect you will put:
what you expect and what the actual value is
For example:
What is it in Rspec
A test error is at the ruby error level: So like ruby is telling you that you have a syntax error or that you are missing something in you code like a method, class or arguments
A failure error is when the test cant not meet the expectations that you have set up
What is test error vs a failure error in Ruby
nil is the default value that a empty method returns
What is nil in ruby?
Sweep gives you options to automatically delete all incoming email from a particular sender, to keep only the latest email, or to delete email older than 10 days. Select an email message from the sender whose messages you want to delete.
What is the sweep function
Ruby also has the redo statement, which causes the current loop iteration to repeat.
The retry statement causes the whole loop to start again from the beginning.
Retry and Redo in Ruby
Ruby blocks are anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or curly braces {}. do-end is usually used for blocks that span through multiple lines while {} is used for single line blocks. Blocks can have arguments which should be defined between two pipe | characters.
Ruby blocks
Another looping statement in Ruby is the loop do statement.
It allows code to execute until a break condition is achieved.
loop do
Rails session is only available in controller or view and can use different storage mechanisms. It is a place to store data from first request that can be read from later requests.
A session in Ruby
A namespace is a container for multiple items which includes classes, constants, other modules, and more. … The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name. The name of namespaces and classes always start from a capital letter.
What are namespaces in Ruby?
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. … The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers.
What is cross domain HTTP request?
A middleware component sits between the client and the server, processing inbound requests and outbound responses, but it’s more than interface that can be used to talk to web server. It’s used to group and order modules, which are usually Ruby classes, and specify dependency between them.
middleware
The HTTP HEAD request is used to check the availability, size, and last modification date of a resource without downloading it (as indicated by the Content-Length and Last-Modified headers). For example, we can send a GET request to check if a PDF file is available for download.
What is the purpose of using HEAD requests?
Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller.
A resource in ruby on rails
Active Model Serializers
A third part Gem thats allows you to contort the Json that comes back
According to Microsoft documentation: Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database or file. Its main purpose is to save the state of an object in order to be able to recreate it when needed.
What does a Serializer do?
ActiveModel::Serializer, or AMS, provides a convention-based approach to serializing resources in a Rails-y way. … At a basic level, it means that if we have a Post model, then we can also have a PostSerializer serializer, and by default, Rails will use our serializer if we simply call render json: @post in a controller.
For Python….
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.
What is Active model Serializer?
The pipe bars essentially make a new variable to hold the value generated from the method call prior
What do pipes mean in Ruby?
In Rails, an association is a connection between two Active Record models. Why do we need associations between models? Because they make common operations simpler and easier in your code. For example, consider a simple Rails application that includes a model for authors and a model for books.
In Rails, an association is?
What is Has_many in Ruby?
Ruby on Rails ActiveRecord Associations has_many
A has_many association indicates a one-to-many connection with another model. This association generally is located on the other side of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model.
What is Has_many in Ruby?
Ruby on Rails ActiveRecord Associations has_many
An HTTP request is made by a client, to a named host, which is located on a server. The aim of the request is to access a resource on the server. To make the request, the client uses components of a URL (Uniform Resource Locator), which includes the information needed to access the resource.
What is HTTP request example?
HTTP works as a request-response protocol between a client and server. Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.
An HTTP request and an example
Why API versioning is required?
Versioning helps us to iterate faster when the needed changes are identified in the APIs. Change in an API is inevitable as our knowledge and experience of a system improve. Managing the impact of this change can be quite a challenge when it threatens to break existing client integration
API versioning helps alter an API’s behavior for different clients. An API version is determined by an incoming client request and may either be based on the request URL or on the request headers. There are a number of valid approaches to versioning.
Why API versioning
In short, CORS is an HTTP-header based security mechanism that defines who’s allowed to interact with your API. CORS is built into all modern web browsers, so in this case the “client” is a front-end of the application. In the most simple scenario, CORS will block all requests from a different origin than your API.
CORS
API headers are like an extra source of information for each API call you make. Their job is to represent the meta-data associated with an API request and response. If you ever encounter issues with an API, the first place you should look is the headers, since they can help you track down any potential issues.
API headers
So, here comes the idea of Object Relational Mapping(ORM). And it is a programming technique for converting data between incompatible type systems using object-oriented programming languages.
It means you can write database queries using the object oriented paradigm of your preferred language and there are many free and commercial packages available that perform object relational mapping.
ORM sets the mapping between the set of objects which are written in the preferred programming language like JavaScript and relational database like SQL. It hides and encapsulates the SQL queries into objects and instead of SQL queries we can use directly the objects to implement the SQL query.
ORMs explained
Data curation is the organization and integration of data collected from various sources. It involves annotation, publication and presentation of the data such that the value of the data is maintained over time, and the data remains available for reuse and preservation.
What is curation in big data?
A temporary way of dealing with a problem or satisfying a need.
Stop-gap
frozen_string_literal: true
class Users::RegistrationsController < Devise::RegistrationsController
def create
resource = ::Users::Signup.call params
if resource.persisted? if resource.active_for_authentication? set_flash_message! :notice, :signed_up sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}" expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource set_minimum_password_length respond_with resource end end end
starting point in the new controller
The keyword self in Ruby enables you to access to the current object — the object that is receiving the current message. … Using self inside an instance or class method refers to the same object the method is being called on, i.e., and instance and class respectively. In an instance method such as #say_hi, using self
What is self in Ruby
In short, JWTs are used as a secure way to authenticate users and share information. Typically, a private key, or secret, is used by the issuer to sign the JWT. The receiver of the JWT will verify the signature to ensure that the token hasn’t been altered after it was signed by the issuer.
What are JWTs?
What are cookies in a website?
Cookies are files created by websites you visit. They make your online experience easier by saving browsing information. With cookies, sites can keep you signed in, remember your site preferences, and give you locally relevant content. … First-party cookies are created by the site you visit.
What are cookies in a website?
Self in ruby defines the method. The method will be a class method
more on self
In fact, we interact with API’s every time we make a browser request (type a site into our browser and press enter).
API’s Basics
One common use of form objects is to reduce complexity in the controller, and the model, which isn’t incorrect, but does not do justice to the important role that they play.
Form objects part One
As much as possible, you don’t want your models to know about each other beyond the associations, which we can consider to be persistence logic. Business logic that spans across multiple models are best kept outside of the ActiveRecord models (form objects are models too, so let’s make the distinction clear). More on this later, if you aren’t convinced.
Form objects part Two
A session is just a place to store data during one request that you can read during later requests.
A session is
Indicates that the user represented by the sealed client-principal object (in the LOGIN state) has logged out of their current user login session. This is a general purpose method an application can use to invalidate, or terminate access to, a sealed client-principal object.
What method is logout?
frozen_string_literal: true
require “rails_helper”
RSpec.describe “[DELETE] /api/v1/logout”, type: :request do
Given(:path) { “/api/v1/logout” }
Given(:user) { FactoryBot.create :user }
context “with vaild params” do
before do
sign_in user
end
When { delete path } # Then { expect(response).to be_successful } Then { binding.pry expect(response).to be_successful }
end
end
web side delete test
Headers in a HTTP request or response is the additional information that is transferred to the user or the server. In postman, the headers can be seen in the Headers tab.
Headers in a HTTP request or response
2xx successful – the request was successfully received, understood, and accepted. 3xx redirection – further action needs to be taken in order to complete the request. 4xx client error – the request contains bad syntax or cannot be fulfilled.
2xx, 3xx, 4xx
What are resources in Ruby on Rails?
Any object that you want users to be able to access via URI and perform CRUD (or some subset thereof) operations on can be thought of as a resource. In the Rails sense, it is generally a database table which is represented by a model, and acted on through a controller
What are resources in Ruby on Rails?
This is how we can modify the reset_password_token using devise with the least possible code changes. It involves understanding the flow of logic throughout the different components in devise, as well as the role each component play, so that you know what can and should be modified. The same can be applied to the confirmation flow as well.
understanding the flow of logic
A flash message is a way to communicate information with the users of your Rails application so they can know what happens as a result of their actions. Example messages: “Password changed correctly” (confirmation) “User not found” (error)
A flash message
What is logic flow in programming?
Flow control is a high-level way of programming a computer to make decisions. These decisions can be simple or complicated, executed once or multiple times. Logic presents rules that allow you to build up and represent more complex ideas. …
What is logic flow in programming?
The show method displays only further details on a single book. This functionality will be achieved by the following lines of code. The show method’s @book = Book. find(params[:id]) line tells Rails to find only the book that has the id defined in params[:id].
What is a show method in ruby?
Rails framework allows complex objects to be stored in a database column via the ActiveRecord::Serialization module. But understanding when to store serialized data in a column is more crucial than knowing how to do it. Through this article, we will first learn “when” to store serialized data and then the “how” part.
Serialization in Rails for Storage
Normalization is a database design technique that reduces data redundancy and eliminates undesirable characteristics like Insertion, Update and Deletion Anomalies. Normalization rules divides larger tables into smaller tables and links them using relationships. The purpose of Normalisation in SQL is to eliminate redundant (repetitive) data and ensure data is stored logically.
What is Normalization?
Storing serialized data in the database could open up a can of worms if we are not mindful. Following are some of the conditions when you may avoid serializing the data:
1) You need to query the serialized data across the records quite often.
When should you not store serialized data?
Storing serialized data in the database could open up a can of worms if we are not mindful. Following are some of the conditions when you may avoid serializing the data:
1) You need to query the serialized data across the records quite often.
2) The state of the serialized data would change frequently. This would need frequent updates to the serialized column which can be a heavy operation.
3) There is a possibility that the field/property name of an object would change in future. (Note: This is not a pressing issue as we do have ways to fix this as explained in the Custom Serializer section below.)
Once you are convinced that all the above criteria do not apply to your use-case, you may go ahead and implement serialization for storing the data.
When should you not store serialized data?
The term DSL is also used to describe some of the concepts in ActiveRecord, which is part of Ruby on Rails. The concept of a DSL is actually unrelated to Ruby, and has been around for a long time. It’s generally used to describe a language that has constructs suited for expressing concepts of a particular domain.
What is a DSL and how does it pertain to Ruby?
2 Answers. Generally asset is anything that browser loads after it gets the HTML page. Meaning javascript, css and any images
What is assets in Ruby on Rails?
Sprockets is a Ruby library for compiling and serving web assets. Sprockets allows to organize an application’s JavaScript files into smaller more manageable chunks that can be distributed over a number of directories and files. It provides structure and practices on how to include assets in our projects.
What are sprockets in rails?
An index is a numerical representation of an item’s position in a sequence. This sequence can refer to many things: a list, a string of characters, or any arbitrary sequence of values. In some programming languages, an array can be defined by key-value pairs, where a specific key points to a value.
What is an Index in Coding?
1 Answer. The purpose of the . call method is to invoke/execute a Proc/Method instance.
What does .call do in Ruby?
Image result for what does .map do in ruby
Map is a Ruby method that you can use with Arrays, Hashes & Ranges. The main use for map is to TRANSFORM data. For example: Given an array of strings, you could go over every string & make every character UPPERCASE.
What does .MAP do Ruby?
rails g pipeline Api::V1::CompanyLead show create index update destroy
An example for when you need to generate the structure for our api endpoints.
create app/controllers/api/v1/company_leads_controller.rb
create app/pipelines/api/v1/company_lead_pipeline.rb
create app/serializers/api/v1/company_lead_serializer.rb
create app/services/api/v1/company_leads/create.rb
create app/services/api/v1/company_leads/update.rb
create app/services/api/v1/company_leads/destroy.rb
create spec/requests/api/v1/company_leads/index_spec.rb
create spec/requests/api/v1/company_leads/show_spec.rb create spec/requests/api/v1/company_leads/create_spec.rb create spec/requests/api/v1/company_leads/update_spec.rb create spec/requests/api/v1/company_leads/destroy_spec.rb
route namespace :api do
CompanyLead
Index shows the list of resources, but likely only an abbreviated portion of those resources.
Show shows the full details of a single resource. potentially with more information from other resources.
Index VS Show
A blob is a record that contains the metadata about a file and a key for where that file resides on the service. … Subsequent to the file being uploaded server-side to the service via create_after_upload!.
What is active storage blob?
Functional programming lets you describe what you want to do, as opposed to how you want it done. An example of what would be “Give me all the even numbers in this list.“. You don’t really care about how it’s doing it, you’re telling it what you want
Functional programming
What the pluck () function does is that it essentially loops through a collection and collects all the data from the particular field and stores it in another collection. That would mean, it plucks the concerned value from a large set of data and stores them in a separate collection for later usage.
How does pluck work?
new is a class method, which generally creates an instance of the class (this deals with the tricky stuff like allocating memory that Ruby shields you from so you don’t have to get too dirty). Then, initialize , an instance method, tells the object to set its internal state up according to the parameters requested
What does New do in Ruby?
The call() method calls a function with a given this value and arguments provided individually.
call() method
What happens after you call map?
Map returns a new array with the results.
It won’t change the original.
If you want to change the original array you can use map!.
Map Method in Ruby
git restore spec/serializers/api/v1/user_lead_serializer_spec.rb
git restore work if you have not committed your code and need to restore your code within some file back to its original state.
Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, −, or backslash at the end of a line, they indicate the continuation of a statement.
Line Endings in Ruby Program
Ruby is a perfect Object Oriented Programming Language. The features of the object-oriented programming language include −
Data Encapsulation
Data Abstraction
Polymorphism
Inheritance
Ruby is a perfect Object Oriented Programming Language
Variables in a Ruby Class
Ruby provides four types of variables −
Local Variables − Local variables are the variables that are defined in a method. Local variables are not available outside the method. You will see more details about method in subsequent chapter. Local variables begin with a lowercase letter or _.
Instance Variables − Instance variables are available across methods for any particular instance or object. That means that instance variables change from object to object. Instance variables are preceded by the at sign (@) followed by the variable name.
Class Variables − Class variables are available across different objects. A class variable belongs to the class and is a characteristic of a class. They are preceded by the sign @@ and are followed by the variable name.
Global Variables − Class variables are not available across classes. If you want to have a single variable, which is available across classes, you need to define a global variable. The global variables are always preceded by the dollar sign ($).
Variables in a Ruby Class
Class methods can only be called on classes
Instance methods can only be called on instances of classes
Class methods are always defined def self.method_name
Instance methods are always defined def method_name
Instance methods vs class methods
Classes are a grouping of methods that exist to construct an object by creating a new instance of the class. Instances are the objects created by a class.
Instance methods vs class methods part: 2
A class is the blueprint from which individual objects are created
Duh
A class is the blueprint from which individual objects are created
Yup
rails db:migrate:status
db migrate
rails db:migrate:status
db migrate status
find_by will not throw an error but find will
find vs find_by
When installing a gem make sure not to use install because that will install it locally and so you need to store the gem inside the gem file
Gem Install
lead = Lead.first
var = model.method. The model has the data base associations which all have values
bin/rails generate pipeline Api::V1::Map_Areas::Contact create update destroy
Generate Leads contacts
contact = ::Api::V1::Leads::Contacts::Create.call contact_params
might need
The backend validators generate errors, they pass errors to the Front-End
Backend Validators in Ruby
The “newer” syntax is only for symbols.
{hello: ‘world’} is equivalent to {:hello => ‘world’} but if your key is a string then you still have to use the “hash rocket” syntax: {‘hello’ => ‘world’}
For symbols.
Ruby operators
The following table shows common Ruby operators ordered by precedence (highest precedence first):
Category Symbol
Resolution, access operators :: .
Array operators [ ] [ ]=
Exponentiation **
Not, complement, unary plus, minus ! ~ + -
Multiply, divide, modulo * / %
Addition, subtraction + -
Shift operators «_space;»
Bitwise and &
Bitwise or, logical or ^ |
Relational operators > >= < <=
Bitwise or, logical or ^ |
Equality, pattern match operators <=> == === != =~ !~
Logical and &&
Logical or ||
Range operators .. …
Ternary ?:
Assignment operators = += -= *= **= /= %= &= |= ^= «=»_space;= ||= &&=
Alternate negation not
Alternate logical or, and or and
Ruby operators
The following table shows common Ruby operators ordered by precedence (highest precedence first):
Persisted if the contact saved than the contact persisted but if the contact did not save than it did not persist
Persisted in Ruby
devise-jwt is a devise extension which uses JWT tokens for user authentication. It follows secure by default principle. This gem is just a replacement for cookies when these can’t be used. As cookies, a token expired with devise-jwt will mandatorily have an expiration time.
devise-jwt
Class variables begin with @@ and must be initialized before they can be used in method definitions.
Class variables
When an uninitialized local variable is referenced, it is interpreted as a call to a method that has no arguments.
Uninitialized local variable
Ruby Constants
Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally.
Constants may not be defined within methods. Referencing an uninitialized constant produces an error. Making an assignment to a constant that is already initialized produces a warning.
Ruby Constants
Ruby Pseudo-Variables
They are special variables that have the appearance of local variables but behave like constants. You cannot assign any value to these variables.
self − The receiver object of the current method.
true − Value representing true.
false − Value representing false.
nil − Value representing undefined.
__FILE__ − The name of the current source file.
__LINE__ − The current line number in the source file.
Ruby Pseudo-Variables
Example
123 # Fixnum decimal
1_234 # Fixnum decimal with underline
-500 # Negative Fixnum
0377 # octal
0xff # hexadecimal
0b1011 # binary
?a # character code for ‘a’
?\n # code for a newline (0x0a)
12345678901234567890 # Bignum
Ruby Literals and Integers
http://localhost:3000/rails/info/routes
Looking up routes on the front-end side
Example
123 # Fixnum decimal
1_234 # Fixnum decimal with underline
-500 # Negative Fixnum
0377 # octal
0xff # hexadecimal
0b1011 # binary
?a # character code for ‘a’
?\n # code for a newline (0x0a)
12345678901234567890 # Bignum
Ruby Literals and Integers
open coverage/index.html
The coverage plugin helps you know how much your test covers
create app/controllers/api/v1/notes_controller.rb
create app/pipelines/api/v1/note_pipeline.rb
create app/serializers/api/v1/note_serializer.rb
create app/services/api/v1/notes/create.rb
create app/services/api/v1/notes/update.rb
create app/services/api/v1/notes/destroy.rb
create spec/requests/api/v1/notes/create_spec.rb
create spec/requests/api/v1/notes/update_spec.rb
create spec/requests/api/v1/notes/destroy_spec.rb
Generated paths for notes
ActiveRecord::Base.connection.tables
ActiveRecord::Base.connection.columns(‘projects’).map(&:name)
Grabbing tables in ruby console
https://apidock.com/rails/ActionController/Parameters/permit
https://apidock.com/rails/Hash/slice
Examples for permit
and slice
Two services folders exist one is for spec and the other is for normal services
Service folder structure