Observer Design Pattern in Ruby


Bookmark and Share

Observer design pattern (also known as Publish/Subscribe) is a software design pattern, used when we are building a system where the state of one object affects the state of other objects. It is a key part of model-view-controller architectural pattern.

In a traditional MVC ( Model-View-Controller ) architecture, a model is a subject and a view is an observer. A view is notified when a model changes and responds accordingly. When the subject sends observers detailed information about what has changed, indiscriminately, this is known as the push model of the Observer pattern. When a subject sends only minimal information to its observers must ask for details explicitly, this is known as the pull model of the Observer pattern.

Observer Design Pattern

Ruby provides a simple mechanism to implement this design pattern using the Observable module. In this mechanism, the Notifier class uses the Observable module, which provides the methods for managing the associated observer objects.

The observable object must:

  • assert that it has #changed
  • call #notify_observers

An observer subscribes to updates using #add_observer, which also specifies the method called via notify observers. The default method for notify observers

Read More

Cheat sheet for managing files from Ruby


Bookmark and Share

In this Cheat sheet, you will learn managing files from Ruby.

Files are used for storing the Data for a Long time Period. And the files can contain any type of information means they can Store the text, any Images or Pictures or any data in any Format. It is associated with class IO File includes.

Creating a New File

New files are created in Ruby using the new method of the File class. The new method accepts two arguments, the first being the name of the file to be created and the second being the mode in which the file is to open. Like,

file = File.new(“filename”, “mode”)

Eg:

Supported modes are:

r
Read only access.

r+
Read and write access.

w
Write only access.

w+
Read and write access.

a
Write only access.

a+
Read and write access.

Opening Existing Files

You can open the existing files using the open method.

Eg:

If the file is already opened, we can close it by using the close method.

Eg:

Reading and Writing Files

Once we’ve opened an existing file or created a new file we need to be able to read from and write to that file. We can read/write using different methods.

sysread Method:

You can use the method sysread to read the contents of a file.

Eg:

This statement …

Read More

Rails Generators


Bookmark and Share

Rails generators are used to create many files for models, controllers, views, unit tests, migrations and more. It will do some of the manual work for us. So it saves time. They can also be used to set up some basic specs for the application test suite.

Running rails generate(or rails g) by itself gives a list of available generators:

The main generators that rails offers are:

  • controller: The Rails controller coordinates the interaction between the user, the views, and the model.
  • helper: Code in helpers is included in the corresponding view. We can move big loops, method calls or other logic into a method in the helper.
  • mailer: It allows for sending and receiving emails from and to your application.
  • migration: Rails Migration allows you to use Ruby to define changes to your database schema.
  • model: It is Ruby class that talk to the database, store and validate data, perform the business logic.
  • scaffold: It refers to the auto-generation of a simple set of a model, views and controller usually for a single table.

Following is the list of options, which can be used along with generators:

-h, [–help] # Print generator’s options and usage
-p, [–pretend] # Run but do not make any changes
-f, [–force] …

Read More

PostgreSQL 9.6 new features


Bookmark and Share

POSTGRESQL is an open-source object-relational database system. It is not controlled by any corporation or other private entity. The source code is available free of charge. PostgreSQL supports transactions, subselects, triggers, views, foreign key referential integrity, and sophisticated locking.

New features in Postgres are:

  • Parallel execution of sequential scans, joins and aggregates.
  • Avoid scanning pages unnecessarily during vacuum freeze operations.
  • Synchronous replication now allows multiple standby servers for increased reliability.
  • Full-text search can now search for phrases (multiple adjacent words).
  • postgres_fdw now supports remote joins, sorts, UPDATEs, and DELETEs.
  • Substantial performance improvements, especially in the area of scalability on multi-CPU-socket servers.

Parallel execution of sequential scans, joins and aggregates

PostgreSQL can devise query plans which can leverage multiple CPUs in order to answer queries faster. This feature is known as the parallel query. Mostly, queries that touch a large amount of data but return only a few rows to the user will get benefit by using Parallel Query. It can now execute a full table scan in multiple parallel processes, up to the limits set by the user.

Avoid scanning pages unnecessarily during vacuum freeze operations

Freezing …

Read More

Concurrent-Ruby


Bookmark and Share

Concurrent Ruby

Concurrent-ruby is a gem that was brought my attention during Anil Wadghule’s talk in RubyConf India 2017.

Concurrency is the ability of a program to make progress on a task that is spread out over different slices of time. It allows us to run multiple “threads” at the same time. As one thread may be sleeping or waiting on I/O, another thread may take priority and start working, thus making optimal use of available CPU time. When you think of concurrency, think of “threads”.

Modern concurrency tools include agents, futures, promises, thread pools actors, supervisors etc.Concurrent Ruby makes the strongest thread safety guarantees of any Ruby concurrency library. Every abstraction in this library is thread safe. Similarly, all are deadlock free and many are fully lock free.

Concurrency Abstractions

  • Async (Concurrent::Async): A mixin module that provides simple asynchronous behavior to a class, turning it into a simple actor.
  • Future (Concurrent::Future): An asynchronous operation that produces a value. It represents a promise to complete an action at some time in the future.
    • Dataflow: Built on Futures, Dataflow allows you to create a …
Read More

Custom Loggers


Bookmark and Share

Custom loggers are useful if you wish to have a separate log file for different moving parts of your Rails application. This would make your logging more efficient and readable. (Eg: a file to record all the API request you received). Let’s have a look on them!

Note: This could cause an issue of log files growing and consuming the entire space in the hard disk can be managed by configuring Rails application. It is described in our previous article Enable log rotation within the rails application.

Rails make use of ActiveSupport::Logger class to write log information. It is used to output message and has associated levels. You can then give the Logger a level, and only messages at that level or higher will be printed. They are:

UNKNOWN
An unknown message that should always be logged.

FATAL
An un-handleable error that results in a program crash.

ERROR
A handleable error condition.

WARN
A warning.

INFO
Generic (useful) information about system operation.

DEBUG
Low-level information for developers.

CREATE YOUR CUSTOM LOGGER

It creates a custom_logger.rb file. Here defines the format for log messages. The arguments are:

  • Severity of the log message
  • Time instance representing when the message was logged
  • progname configured or passed to the logger method
  • Object the user passed to the …
Read More

Enumerator: When to Use and Why are they so special?


Bookmark and Share

In this post, we’ll take a look at the basics of Enumerator, When to use it and Why they are so special. So let’s begin!

As the name implies Enumerator is used for iterating over a collection of items. It allows both internal and external iteration.

So how do we Create an Enumerator?

There are 3 different ways to create it. They are from,

  • A Block,
  • An Enumerable,
  • A Blockless Enumerable Method Call.

Let’s have a look on each of the method now.

From a Block

We can create an enum by passing a block to its constructor. A yielder object will be passed to this block. The yielder’s #<< method can be used to define the elements. Enumerator#next can then be used to provide iteration.

Eg:

From an Enumerable

The most common way to create an Enumerator is from an Enumerable object, specifically, an object that defines a #each method. Object#to_enum is implemented to return a new Enumerator which will enumerate by sending #each to its receiver.

Eg:

From a Blockless Enumerable Method Call

There are several Enumerable methods that take a block and returns an Enumerator when called without a block. For instance, calling Array#select without a block will return an Enumerator with an #each method that will filter like #select.These blockless calls …

Read More

Spice up your boring IRB (Irbtools)


Bookmark and Share

IRB stands for interactive ruby, it is a tool for interactively executing ruby expressions read from a standard input. To invoke it, type irb at the shell or command prompt, and begin entering Ruby statements and expressions. But it has some limitations. A solution to this is called ‘irbtools‘, which make using irb easier and more fun. It improves Ruby’s irb console like colored output and lots of helpful methods.

Setup

Install the gem by using:

or

Add it to your project’s Gemfile:

Usage

IRB executes code in ~/.irbrc on start-up.To use irbtools, put the following code in ~/.irbrc file:

We can start IRB directly from the code by calling,

When installing irbtools, some gems will not be installed. For example, the bond gem for better auto-completion. These are packaged as irbtools-more (requires ruby version >= 2.4). To use irbtools-more, change the .irbrc to:

and edit Gemfile as

For example, the output looks like:

Irbtools

Features

  • Colorized and output as comment by wirb and fancy_irb
  • Nice IRB prompt and IRB’s auto indention
  • Includes stdlib’s FileUtils: ls, cd, pwd, ln_s, rm, mkdir, touch, cat
  • Many debugging helpers:
    • ap – awesome_print
    • q –like p, but on …
  • Read More

    PStore, a little known feature in the standard library


    Bookmark and Share

    PStore(persistent store) implements a file based persistence mechanism based on a Hash. It writes Ruby objects to an external file so it can access easily if needed. If an I/O error occurs while PStore is writing to its file, then the file will become corrupted.You can prevent this by setting pstore.ultra_safe = true. Also, it supports thread-safe and uses Marshal internally.

    To use this library, you must require it and instantiate a new object.

    Which would create a file that stores the content to be written.

    To store or retrieve data from the data store, you must open a transaction. Here transaction is a protective wrapper around SQL statements to ensure changes to the database only occur when all actions succeed together. We can access the content of database only through this transaction.

    At the end of the transaction, all changes are committed.

    Public Instance methods

    Instance methods are methods that are called on an instance of a class. We can use the below methods while using PStore instances.

    • p[name]=obj

    Stores obj in the database under the key name. When the transaction is completed, all objects accessed reflexively by obj  are saved in a file.

    • p.root?(name)

    Returns true if the key …

    Read More

    Disabling transaction block during migration


    Bookmark and Share

    Migrations are used to modify your database. By default, all migrations run inside a transaction. You can disable the transaction during migration. Let’s have a look on how to disable transaction block!

    Migrations can manage the evolution of a schema used by several physical databases. It’s a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server. With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind.

    In Rails, transactions are protective blocks around SQL statements that ensure changes to the database only occur when all actions succeed together. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction block whenever you have a number of statements that must be executed together or not at all.

    Eg:

    disable_ddl_transaction!()

    DDL can’t run inside a transaction block. You can disable DDL transactions in Rails, using disable_ddl_transaction. It is used in …

    Read More