Rails Knowledge Flashcards
Class Method vs Instance Method
Class methods are available on classes and Intance methods on intances.
Typically used differently - class methods used to do things on the broader scope of all instances of the class (count number of articles by a particular author) where instance methods are used to do things on a single particular instance (count number of words in this specific article)
What is a PORO?
“Plain Old Ruby Object” ; Although almost everything in Ruby is an object, ActiveRecord tends to use a lot of complex objects so the term PORO is typically used to describe a “small, simple object used to support business logic”
Does Ruby allow multiple inheritances?
No, it does not allow inheriting from more than one parent class, but it does allow module mixins with “include” and “extend”
Is Ruby “strongly” or “weakly” typed?
Strongly. An error will be thrown if you try to calculate “hello” + 3
in contrast, Javascript would calculate the same as “hello3”
What frameworks have you used for backgrounding jobs?
Sidekiq
* it uses Redis to queue jobs which is an “in-memory data store” so it is very fast
* Sidekiq adds complexity to infrastructure because of its need for redis
* we already used redis so this wasn’t an issue for us
Others out there:
* Delayed::Job - Easy to setup and use. Queues are store in DB. Could turn DB into bottleneck if same DB used for production
* Sucker Punch - Runs as a Ruby process and keeps all jobs in memory. Jobs are thus lost if the process crashes. Not recommended for critical tasks
How to declare a constructor on a Ruby class
Constructor = initialize method
initialize is called when a new instance of a class is initialized (i.e. .new is called on the class)
- Defining this method is not required
- Often used to provide attribute values on new instances
class Thing
attr_reader :name
def initialize(name)
@name = name
end
end
t = Thing.new(‘dog’)
puts t.name # => ‘dog
What logic goes into a “helper”?
Helper logic should support Views only
A good candidate for a helper would be date formatting logic required in several different views
What is ActiveRecord?
An ORM (Object-Relational Mapping) that maps models to db tables. It simplifies setting up an App because we no longer have to write SQL directly in order to load, save, or delete objects.
It also provides some protection against SQL injections
When do we use “self” in Ruby
When we’re calling class methods - when we’re trying to perform an action on the entire class of an object rather than just one instance
- When defining and calling class methods
- self refers to the current class, so its required when a class method calls another class method
- self.class.method is required when an instance calls a class method
What is “Rack”
Rack is an api sitting between the web server and Rails. It allows plugging in a swapping frameworks like Rails with Sinatra, or web servers like Unicorn with Puma
What is MVC?
Model View Controller
A software design pattern that Rails is built around. It splits the handling of information into 3 pieces.
The Model manages the data logic
The View displays the information
The Controller takes input and prepares data for a model or view
What is a block in Ruby?
A block is the code between two curly braces {} or b/w a “do” and “end”
You’re passing a block every time you call .each
Blocks have their own scope. Any variables defined only inside the block are not accessible outside of it, but variables defined outside of it can be modified inside the block
What is the difference between a Proc and a Lambda?
Both Procs and Lambdas are stored blocks but syntax and behavior differ slightly:
A lambda returns from itself, but a proc returns from the block it is inside of
What is “yield” in Ruby?
Yield accesses a block passed to a method. Its typically used in layout files in Rails apps
What is content_for for?
It allows rendering content in views.
Useful for defining content in one place and rendering it in many
What is the difference between Hash and JSON?
Hash is a Ruby class - a collection of key-value pairs that allows accessing values by keys
JSON is a string in a specific format for sending data
What is ActiveJob?
Allows creating background jobs and queueing them on a variety of backends like Sidekiq and Delayed::Job
Its typically used to execute code that doesn’t need to in the main web thread
Common use case is sending notification emails to users
What do you like about Rails?
- I like the readability of it
- I like the structure and repeatability that provides
- I like being able to use ActiveRecord and its various tools to simplify DB manipulation/management
- It’s fun
- an amazing community that is super helpful and great examples and documentation is easy to find
- Convention over configuration means you generally know where to find things when navigating a new/large codebase especially compared to frameworks that prefer configuration like Django
What do you dislike about Rails?
- Machine learning libraries are poorly developed or non existent
- Runtime Speed and Performance. One of the most frequent arguments against RoR is its ‘slow’ runtime speed, which makes it harder to scale your RoR applications
- Lack of Flexibility
What is your favorite Ruby Gem?
- Pry
- Faker - for test data
- graphql-fragment-cache
- annotate
- “Devise” for setting up authentication in a breeze
What is Spring?
Spring is an application preloader
It keeps the application running in the background so the so that booting is not required any time you run a migration or rake task
What is asset pipeline?
Its a framework that prepares Javascript and CSS for the browser
How have you managed authentication in rails?
TODO
What is the splat operator?
Splat is used when you don’t want to specify the number of arguments passed to a method in advance.
It is “*”
There is a single splat and a double splat in Ruby
Double receives key value pairs
Difference between include and extend?
Both are mixins that allow injecting code from another module
But include allows accessing that code via class methods, while extend allows accessing that code via instance methods (This might be backwards)
What is the difference between load and require?
load runs another file even if it’s already in memory
require will only run another file once, no matter how many times you require it
What is the diff b/w a class and a module?
A class has attributes and methods.
A module is just a collection of methods and constants which you can mixin with another module or class
What’s a “scope”?
A scope is ActiveRecord query logic that you can define inside a model and call elsewhere
Defining a scope can be useful instead of duplicating the same logic in many places in the app
What is the diff b/w class and instance vars?
Instance variables denoted by the “@” are associated with an instance of a class.
Changing the value of an attribute on one instance will have no effect on the variable for another instance
Class variables denoted by “@@” are less intuitive. They are shared across all instances of the class. So, changing the variable on once instance DOES affect the variable for all instances
What is the difference between find, find_by, and where in ActiveRecord?
.find takes a single argument and looks up the record where the primary key matches that argument
.find_by takes key/values and returns the first matching record
.where takes key/values and returns a collection of matching records. Or an empty collection if there are no matching records
What is the difference between select, map, and collect?
.select is used to grab a subset of a collection. using .select! with a bang mutates the original collection
.map performs an action on each element of a collection and outputs an updated collection. Calling .map! with a bang mutates the original collection
.collect is an alias of .map and does the same thing
What are the CRUD verbs and actions in Rails?
CRUD - Create, Return, Update, Destroy
verb action
GET index
GET new
POST create
GET show
GET edit
PATCH/PUT update
DELETE destroy
Define a route for a create action without using “resources”
with resources:
resources :photos
without:
post /photos
, to: photos#create
, as: :create_photo
what are the three levels of access control?
public, private, protected
public: Any object can call this method
protected: Only the class that defined the method and its subclasses can call the method
private: Only the object itself can call this method
How to use singletons in Ruby?
A singleton is a design pattern that only allows a class to have one instance.
This is typically frowned upon in Ruby, but ruby does come with a module for it
require ‘singleton’
class Thing
include Singleton
end
puts Thing.instance
# => #<Thing:0x00007fdd492cf488>
What is a Microservice and what is microservice architecture?
What is Ruby on Rails
An open-source, web-application framework. Built within the Ruby programming language, it helps people create web apps quickly and efficiently by prioritizing conventions over configuration
What do subdirectory app/controllers and app/helpers do
app/controllers help Rails find controller classes and essentially handles a web request from the user, the helper holds any helper classes that assist the controller, model, and view classes.
What command can you use to create a controller for the subject?
rails generate controller Subject
Name five things Rails Migration can do.
renaming a table, adding a column, changing a column, dropping a table, removing a column, changing the data type of a column
What is the Rails Controller?
Rails Controller is the center of your application as it helps the overall user, views, and model interaction.
A controller can thus be thought of as a middleman between models and views. It makes the model data available to the view, so it can display that data to the user, and it saves or updates user data to the model.
How can you protect Rails against Cross-Site Request Forgery?
To protect from any Cross-Site Request Forgery hacker attacks, you need to add ‘protect_from_forgery’ to your ApplicationController.
What does garbage collection do in Ruby on Rails?
Allows the removal of the pointer values that is left behind when the execution of the program ends.
It frees the programmer from tracking the object that is being created dynamically on runtime.
Name three of the limits of Ruby on Rails?
Ruby on Rails has various features that it doesn’t support which makes it unusable for some programmers. This includes linking to more than one database at a time, connecting to more than one database server at a time and foreign key in databases.
What are some advantages of using Ruby on Rails?
Ruby on Rails has various advantages. For one, it makes a programmer’s work more productive. It’s also open-source and completely free. In addition, it provides programmers with the opportunity to write code that acts on actual code rather than data.