0% found this document useful (0 votes)
9 views10 pages

Advanced Programming - Ruby and Rails

Uploaded by

buro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

Advanced Programming - Ruby and Rails

Uploaded by

buro
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Advanced Programming

What is a framework
●​ Is a foundation upon which an application is developed.
●​ Serves as a starting point in developing an application​
●​ It saves developers a lot of effort and time​
●​ It is associated with a specific programing language​
●​ A framework is in control of the code – it creates objects, inject dependencies,
…(inversion of control)​
●​ E.g. Building a house from scratch vs completing it after the structure is finished​
●​ E.g. of framework – RoR, Spring, Laravel, Django, …

Why framework ?
●​ It saves a lot of effort and time - focuses on productivity ​
●​ It is well tested – reduce bugs/ errors​
●​ Easy to maintain and understand - it follows conventions ​
●​ Organizes code better – follows design patterns​
●​ Allows developers to focus on business logic​
●​ Provides tools to develop, test and debug code​
●​ Sets reasonable/ sensible defaults​
●​ Built-in security – security from SQL injection, CSRF​
●​ Provides standard

How does the web work?


●​ It works using a client server architecture​
●​ It uses the HTTP (HyperText Transfer Protocol) to communicate between a client and a
server​
●​ The request ranges from simple get request to fetch a static content to post and delete
requests to add or delete resources on the server ​
●​ Every request and response contains a header and optional body​
●​ Servers are always on and listen to requests from clients and handle them accordingly​
Handling static requests

Handling dynamic request

How does HTTP (Hypertext Transfer Protocol) work?


●​ HTTP is the underlying protocol used by the world wide web and works at application
layer
Cont.
●​ Communication between a host and a client occurs via a request/ response pair. For
example,​
○​ When you type a URL into your web browser and press Enter, your ​
browser sends a request called an HTTP Request to the web server that ​ hosts
the website you want to visit​
●​ The server then sends back an HTTP response, which contains the data for the web
page you requested for​

●​ HTTP methods/ verbs​


○​ They specify the action that should be performed on the host​
○​ GET: fetch an existing resource. The URL contains all the necessary information
the server needs to locate and return the resource​
○​ POST: create a new resource. Post requests usually carry a payload that
specifies the data for the new resource​
○​ PUT: update an existing resource. The payload may contain an updated data for
the resource​
○​ DELETE: delete an existing resource

●​ HTTP status codes​


○​ With URLs and verbs, the client can initiate request to the server. In return, the
server
○​ responds with status codes and message payloads​
○​ 2xx: Successful – this tells the client that the request was successfully processed​
○​ 3xx: Redirection – this requires the client to take additional action​
○​ 4xx: Client error – these codes are used when the server thinks that the client is
at fault, either by requesting an invalid resource or making bad request​
○​ 5xx: Server error – this class of codes are used to indicate a server failure while
processing the request

MVC Design pattern​


●​ It is a software architectural pattern that separates an application into three
interconnected components​
○​ Model​
○​ Manages data and business logic​
○​ Also handles the ORM (object relation mapping)​
○​ View​
○​ Handles the user interface and presentation​
○​ Controller​
○​ Facilitate communication across the application

●​ Advantages​
○​ Separation of concern – makes code clean and organized​
○​ Easy to read and maintain​
○​ Easy to test and debug – isolated testing and debugging​
○​ Improved team collaboration and productivity​
●​ Disadvantages​
○​ It has a learning curve​
○​ Increased complexity – as the app grows the number of files also grow

RESTful API
●​ API provides a way to standardize communication through a set of protocol​
●​ Specifies/ defines methods and data formats for applications to send request and
receive information enabling them to interact and perform specific functions​
●​ Acts as an intermediary allowing developers to access the functionality of other software
systems without needing to understand how those underlying systems work​
●​ It can be better understood by taking a restaurant as an example ​
○​ Client orders food (represents an application that interacts with the API)​
○​ Waiter facilitates interaction b/n the client and server (API)​
○​ Kitchen where the actual task is done (Server)

Ruby Basics
●​ Datatypes​
○​ Symbols​
○​ Arrays​
○​ Hashes​
●​ Class, object, method​
○​ attr_accessor, attr_reader, attr_writer​
●​ Instance variable​
●​ Yield​
●​ Blocks, procs and lambdas​
●​ Looping and iterations

●​ Data types​
○​ Symbols​
○​ A symbol is a unique instance of Symbol which is generally used for identifying a
specific resource (state, method, variable, hash key, etc…) – e.g. status of
account active or inactive​
○​ Start with :​
○​ Are immutable ​
○​ Unlike strings they are not destroyed ​
○​ Are efficient as they are created once and used multiple times​
○​ Array​
○​ A data structure that stores multiple values​
○​ Can contain any value​
○​ Use << to append a new value to an array​
○​ E.g. [1, “Monday”, 2.5, True]
●​ Hashes​
○​ Are like dictionaries​
○​ Have built-in methods​
○​ .merge – merges two hashes and returns a new hash​
○​ .fetch(“key”) – returns a value if the key exists in the hash, otherwise raises an
error​
○​ .keys – returns keys of the hash​
○​ .length/ .size – return the number of key/value pairs within a hash

Class, Object and Method


●​ Classes are blueprints from which objects are created​
○​ E.g ​
​ ​ ​ class Book​​
​ ​ ​ ​ attr_accessor :title, :author, :description, :rating​​
​ ​ ​ end​
●​ attr_accessor – provides the attributes with getters and setters

●​ Objects are instances of a class​
first_book = Book.new()​​
​ first_book.title = "Really Great Book"​​
​ first_book.author = "Denali Balser" ​
​ first_book.description "best book ever"​​
​ first_book.rating = 100​
●​ Methods​
def change_author(obj, new_author) ​
​ ​ obj.author = new_author​​
​ End

●​ Listing methods with .methods​


○​ E.g “test”.methods​
●​ Chaining methods​
○​ E.g “test”.methods.sort​
●​ Initialize method acts as a constructor in ruby class​
●​ Predicate methods – are methods with ? And returns either true or false​
○​ E.g 5.odd?​
●​ Bang methods – are methods that ends with !​
○​ They usually modify the object that they’re being called on​
○​ E.g.​
name = "Ruby Monstas" ​
puts name.downcase!​
puts name

●​ Keyword arguments​
def test(name:, age:) … end​
test(name: “john”, age: 22)​
●​ Instance variables​
○​ Instance variables live in, and are visible everywhere in the object’s scope​
○​ E.g. @name = ”John”​
●​ Yield​
○​ is used inside a method to transfer control to a block that is provided when the
method is called​
○​ It allows you to execute code from the block at a specific point within the method.​
def greet​
puts "Hello,"​
​ ​ ​ yield if block_given? # Executes the block if given​
​ ​ ​ puts "Goodbye!"​
end​
greet { puts "Welcome to Ruby!" }

Blocks, Procs & Lambdas


●​ Are all ways to define chunks of code that can be passed around and executed ​
●​ They are all related to Ruby’s support for first-class functions, meaning functions can be
treated like objects, passed as arguments, or returned from other functions​
●​ Blocks​
○​ Is a chunk of code that you can pass to methods to be executed later​
○​ Blocks can either be passed to a method explicitly or implicitly – implicit if it is not
listed in the parameter list and explicit is the opposite. ​
○​ Use yield to pass it explicitly​

e.g. def greet​ ​ ​ ​ ​ ​ ​ ​


yield(“hello”, “there”)​
end ​
greet { |world1, word2| puts “#{word1} #{word2}” }​
​ ​ ​ OR​
​ ​ [1,2,3].each {|num| puts num*2 }​

def greet(&block)​
puts "Hello!"​
block.call if block​
puts "Goodbye!"​
end​
greet { puts "Nice to meet you!" }​

●​ A block is not an object and can not be stored in variables directly​


○​ Blocks are executed by calling yield inside a method when passed
implicitly​

●​ Procs​
○​ A proc is an object that encapsulates a block of code​
○​ It can be stored in a variable and can be passed around​
○​ It is defined using Proc.new or the proc method​
○​ Procs are called using .call method​
○​ They can have default parameters and return early (using return inside a proc
exits from the method where the proc is called)​

e.g. my_proc = Proc.new { |a,b| puts a + b }​


​ ​ my_proc.call(2,3)​
​ ​ ​ ​ OR​
​ ​ my_proc = proc { |a,b| puts a + b }​
​ ​ my_proc.call(2,3)​

●​ Lambdas​
○​ Is like proc, but with a few key differences​
○​ They are objects with strict argument handling and return behavior​
○​ They are defined using lambda or ->​
○​ The difference with procs is that lambda check the number of arguments and will
raise an error if the number of arguments do not match, and the return keyword
will exit only the lambda itself unlike procs, which exits from the method​
e.g. my_lambda = lambda {|a, b| puts a + b }​
my_lambda.call(2,3)​
​ ​ ​ OR​
​ ​ my_lambda = ->(a,b) {puts a + b }​
​ my_lambda.call(2,3)

Looping and Iteration


●​ While ​
○​ Syntax while condition … end​
●​ Until​
○​ Syntax until condition … end​
○​ The loop get executed until the condition become true​
●​ Times – repeats a block a specified number of times​
○​ E.g. 5.times { |i| puts "Iteration #{i + 1}" }​
●​ Each - Iterates over elements in an array or range​
○​ E.g. [1, 2, 3, 4, 5].each { |num| puts num }​
●​ Map - Transforms each element in an array and returns a new array​
○​ E.g. doubled = [1, 2, 3].map { |num| num * 2 }​
●​ Select - Filters elements based on a condition​
○​ E.g. evens = [1, 2, 3, 4, 5, 6].select { |num| num.even? }
●​ Reject - Opposite of select, removes elements that match a condition ​
○​ E.g. odds = [1, 2, 3, 4, 5, 6].reject { |num| num.even? }​
●​ Find - Finds the first element that matches a condition​
○​ E.g. first_even = [1, 2, 3, 4, 5].find { |num| num.even? }​
●​ Inject / Reduce - Both are the same and used for accumulation (sum, product, etc.)​
○​ E.g. sum = [1, 2, 3, 4, 5].inject(0) { |acc, num| acc + num }​
●​ product = [1, 2, 3, 4].reduce(1) { |acc, num| acc * num }

Introduction to Rails
●​ What is Rails?​
○​ Rails is a web application development framework written in the Ruby
programming language​
○​ It is designed to make programming web applications easier by making
assumptions about what every developer needs to get started​
○​ Rails is opinionated framework - It makes the assumption that there is a "best"
way to do things, and it's designed to encourage that way ​
●​ Creating a rails app​
○​ Run rails new app_name –T​
●​ Important directories​
○​ App - Contains the controllers, models, views, helpers, mailers, jobs, and assets
for your application​
○​ Bin - Contains the script that starts your app and can contain other scripts you
use to set up, update, deploy, or run your application​
○​ Config - Contains configuration for your application's routes, database, and more
●​ Db - Contains your current database schema, as well as the database migrations​
●​ Dockerfile - Configuration file for Docker​
●​ Gemfile / Gemfile.lock - These files allow you to specify what gem dependencies are
needed for your Rails application​
●​ Lib - Extended modules for your application​
●​ Log - Application log files​
●​ Public - Contains static files and compiled assets. When your app is running, this
directory will be exposed as-is​
●​ Tmp - for temporary files​
●​ .git/ .gitignore – git related configs to manage versions and exclude some files/
directories from tracked by git
●​ Starting the rails server​
○​ bin/rails s or bin/rails server​
●​ Models​
○​ Use bin/rails g model model_name field1:type field2:type …​
○​ When running the above command, the model and the corresponding migrations
and test files will be created​
○​ Model name should be singular​
●​ Migration​
○​ Is a set of changes we want to make to a database​
○​ It tells rails how to change the database to add, change or remove tables,
columns or other attributes​
○​ Table names are plural ​
●​ Running migration – bin/rails db:migrate​
○​ It runs new migrations that are not run previously. How does it know?
●​ Reversing a migration​
○​ bin/rails db:rollback – reverts the most recent migration​
○​ bin/rails db:rollback STEP=2 – rolls back the last two migrations​
○​ rails db:migrate:redo - rolls back the last migration and then re-runs it​
○​ rails db:migrate VERSION= migration_version - rolls back all migrations after the
specified version​
○​ bin/rails db:migrate:reset - drops the database, recreates it, and runs all
migrations again from scratch​
○​ rails db:drop db:create db:migrate - drops the database and creates a fresh one
before running all migrations​

Model in Detail
●​ Creating a record​
○​ record = Model.new(field1: value,…, field n: value n), then record.save​
OR
○​ Model.create(field1: value,…, field n: value n)​

●​ Querying records​
○​ all - method fetch all records from the corresponding table​
○​ where – to filter records​
○​ Model.where(field1:value1,…)​
○​ find – returns a specific record and take id of the model​
○​ find_by – returns the first record that matches the criteria​
○​ Model.find_by(field: value)​
○​ instance.update(field1: value1,…) – updates the filed with the new value​
○​ Instance.destroy – deletes the model
●​ Validation​
○​ ensure that only valid data gets saved into the database​
○​ Validation list​
■​ presence: true – requires a filed ​
●​ validates :name, presence: true​
■​ Uniqueness: true - ensures the value is unique in the database​
●​ validates :email, uniqueness: true​
■​ Length - validates string length​
●​ validates :password, length: { minimum: 8 }​
■​ Numericality - ensures a number is valid​
●​ validates :age, numericality: { greater_than: 18 }​
■​ Inclusion - ensures value is in a specific set​
●​ validates :role, inclusion: { in: %w(admin user guest) }​
■​ Exclusion - Ensures value is not in a set​
●​ validates :username, exclusion: { in: %w(admin superuser) }
○​ Custom validation​
■​ You can define custom validations using​
class User < ApplicationRecord​
​ validate :email_must_be_company_domain​
​ private​
​ def email_must_be_company_domain​
​ ​ unless email&.end_with?("@company.com")​
​ errors.add(:email, "must be a company email")​
​ end​
end​
End​
●​ Conditional validation - Validations can be applied conditionally​
validates :password, presence: true, on: :create​
​ ​ validates :discount, numericality: true, if: -> { on_sale? }​

You might also like