Eager Loading

What is Eager Loading ? Eager loading is a mechanism through which ActiveRecord loads the associated records in memory, reducing the number of executed sql queries. There are following ways to do eager loading in ActiveRecord: includes preload eager_load Why do we need Eager Loading ? Let’s say we’ve to get the author’s last name of some books. For that the query will look like: books = Book....

April 11, 2024 · 3 min · Ashish Gaur

Strategy Pattern in Ruby

Strategy pattern is a behavioral pattern which is used when there is a need to choose an algorithm on runtime. It’s a very good example of open/closed principle. What is Open/Closed Principle Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. The idea is to add new functionality without changging the existing classes. So how does Strategy Pattern makes sure open/closed principle is used in our code, lets find out....

October 14, 2023 · 3 min · Ashish Gaur

Builder Pattern in Ruby

What is Builder pattern ? The builder pattern is a creational design pattern used for building complex objects involving several steps to create or require multiple sub objects. The pattern helps in abstracting away the process of instantiating the sub objects and the relationship among them. Builder pattern helps in: Allowing to create different representation of a complex object. Simplifying creating an object with several steps or instantiation of sub objects....

October 8, 2023 · 4 min · Ashish Gaur

Procs Lambdas and Blocks

Blocks Blocks in ruby are anonymous functions that can be passed into methods. Calling Blocks Blocks can be called using the yield keyword or by calling .call, the latter is called an explicit block while the former is called an implicit block. explicit block: Using .call to execute a block def explicit_block(&block) block.call end explicit_block { puts "Explicit block called" } implicit block: using yield to execute a block # block passed as anonymous function def test_method yield end test_method { puts "Block is being run" } # block with parameters def one_two_three yield 1 yield 2 yield 3 end one_two_three { |number| puts number * 10 } # 10, 20, 30 Proc a proc is an instance of the Proc class and is similar to a block....

August 6, 2023 · 3 min · Ashish Gaur

Sessions in Rails

Sessions provide a way to store any kind of data across requests. This could be user info, preferences, cart items etc. Using sessions is fairly easy, Rails provides a session variable which is a dictionary with key-value pairs. # Writes login of the user in the session session[:user_login] = user.login # Reading from session user_login = session[:user_login] Since HTTP is a stateless protocol, sessions comes in handy in retaining info across subsequent requests....

August 6, 2023 · 2 min · Ashish Gaur