Monday, 6 November 2017

How to choose a technology stack for web application development

CRITERIA FOR CHOOSING A TECHNOLOGY STACK

Type of Web Application
The first thing to decide upon is the type of web application you’re developing. A tech stack is a toolset for creating a web app, so you need to fully realize what you’re planning to build in order to pick the appropriate tools. You should find a toolset that provides unique advantages for your web application.
In terms of complexity, all web projects can be divided into three types:
  • Simple. These web applications are created with the help of out-of-the-box solutions (such as CMS software, for example). Examples: landing pages and simple online stores.
  • Mid-level. These apps have more functions than simple apps and are built with the help of frameworks. Examples: apps for large e-commerce stores and enterprises.
  • Complex. These web apps have lots of functions and integrations; they’re developed with the help of different web development technologies and may be composed of several programming languages. Examples: social networks, large e-commerce marketplaces, fintech software, etc.
Knowing the type of web app you’re developing isn’t enough; you should take its business goals into account as well. This is important since your business goals impact the choice of technologies for development. Your web app can be tailored for:
  • Processing heavy loads. If your web project relies on load processing, you should opt for programming languages and frameworks that can provide this. Examples of such projects are video/audio streaming apps and file sharing services.
  • Low latency. A different tech stack is required to make your web application highly responsive and to reduce latency. Social networks are probably the best example of websites that require low latency.

Time to Market

Time to market (TTM) is extremely important when choosing a tech stack for startups and for small businesses. The faster you develop and release your application, the more ahead of competitors you’ll be. Moreover, the less time development requires, the cheaper the development cost.
TTM heavily depends on the technology stack you select for your web application, and here’s a list of issues you should consider when choosing a proper stack:
  • Out-of-the-box solutions. Check whether a technology has some out-of-the-box solutions for adding some necessary functionality to your web application. For example, the Ruby on Rails framework allows developers to use lots of open-source libraries (called gems) that facilitate the development process and significantly reduce TTM.
  • Integration with third-party solutions. Make sure the tech stack you choose supports integration with third-party solutions, as it’ll help you add the functions you need to your web application without reinventing the wheel.
  • Developer availability. Even if you’ve decided upon the tech stack, there’s still a problem: you need developers to do all the coding. You should check whether you’ll be able to find developers with expertise in the technology stack you choose. And remember that building a web application is just the beginning. You also need developers to maintain it after launch.
  • Documentation and developer community. Producing good code is difficult, and any development team may stumble over some tricky issues. It may take quite long for a team to find a solution, which means, in turn, a missed web project release deadline. That’s why you should find out whether the technologies you’re going to select have large developer communities and rich documentation.



image of number of Github contributors

  • Easy to test. A web application contains many lines of code, so bugs are inevitable. Needless to say, removing all bugs requires a lot of time and slows down development. To counter this problem, choose technologies that are easy to test. Some technologies are based on a so-called test-driven development approach, which implies that testing goes first and coding comes after. Test-driven development allows you to guarantee your code and product quality and speed up development in the medium and long term.

Development Cost

Needless to say, turning your idea into a real-life web application isn’t free of charge and requires investment. The choice of a website technology stack has a direct impact on the development cost. There are two main issues you need to take into account:
  • Developer salaries. Web developers are highly skilled professionals who are rather well-paid. Their salaries, however, depend on the technologies they work with. Consequently, your expenses will be different depending on tech stack. You should remember that the more advanced the technology is, the higher the developer salary will be.



image of average developer salaries in the US

  • App maintenance cost. Creating a web application is just one side of the coin; maintaining it is the other. To reduce maintenance costs, you should opt for free open-source technologies. For example, the Ruby on Rails web development framework is available with the MIT licence, which means it can be modified, upgraded, and used without any restrictions.

Security

Our world has gone digital over the last two decades and so have criminals. Cyber attacks are the biggest threat to online businesses: according to a forecast by Juniper Research, annual financial losses from data breaches are expected to reach a mind-blowing $2.1 trillion by 2019. Today, governments and corporations are working hard on ensuring the highest level of cyber security possible.
No doubt, you want your web application to be secure. Hence, you should pick technologies that allow you to create a really secure app. There are lots of different opinions as to which programming language is the safest, but in truth, no language guarantees 100% safety.
Every web development technology serves its purpose, so you should choose the right tool first and follow security guidelines second. Most web development technologies have security guidelines where all steps for preventing threats and minimizing vulnerabilities are given. You need to make sure that your web app is created in accordance with the appropriate security guidelines.

Scalability

Scalability isn’t a feature to turn tail on when developing a web application. No doubt you wish to see your web project grow and gain popularity. In general, there are two kinds of scalability:
  • Horizontal scalability, which means the ability of a web application to accommodate more requests. In other words, an app must be able to work if the number of users grows dramatically.
  • Vertical scalability, which means the ability to add new components to a web application without damaging its performance.
You should think of scalability in advance and choose an appropriate technology stack for your needs. This may seem a difficult choice as you’ll probably come across a number of contradictory opinions. However, we recommend relying not on someone else’s words, but on concrete examples of why exactly a certain technology is scalable.

TECHNOLOGY STACKS BEHIND SUCCESSFUL WEB PROJECTS

By now, you are almost certainly curious about some modern web application stacks. Let’s take a look at what technologies power some of the most successful web projects:



Airbnb, the world’s most well-known hospitality service that helps millions of people find rental apartments and short-term lodging, is largely based on Ruby on Rails.
image of Airbnb stack

Shopify helps entrepreneurs power their online stores. Ruby on Rails is the core technology behind this super-successful web service.
image of shopify stack

Quora is a question-and-answer website where people can find answers to each other’s questions.
image of quora stack

Instagram, a mainstream social networking application, is built with Python.
image of instagram stack

Product Hunt is a popular service that allows users to share information about products and find new products on the web.
image of product hunt stack

Codecademy is an online educational platform that offers free coding classes in 15 programming languages, including Ruby, Python, and Java.
image of codecademy stack

Pinterest is a social network aimed at helping people share and find new interests.
image of pinterest stack

Reddit is a popular news aggregator and discussion platform.
image of reddit stack

Coursera is a venture-backed educational platform that offers a variety of online courses on different subjects.
image of coursera stack

Facebook is the world’s biggest social network with almost 2 billion active monthly users.
image of facebook stack

PICK A TECHNOLOGY STACK ACCORDING TO YOUR PROJECT

As you can see, selecting the right tech stack is a real challenge, but the core idea that should guide you is as follows: choose the technologies according to your project. You shouldn’t rely on time-proven technologies only, even if they have been used by some large and successful companies or prominent projects have been accomplished with their help.
You should always be realistic and take all pros and cons into account. The wrong choice of a technology stack may end in financial losses, so if you aren’t experienced in web development, leave the choice to professionals. A team of professional web developers will be able to choose the right tools for delivering a top-notch web application with all the functionality you need.

Thursday, 13 July 2017

Ruby Exception Handling

What Are Exceptions?

Exceptions are Ruby’s way of dealing with unexpected events.

begin
1/0
rescue
puts "Got an exception, but I'm responding intelligently!"
end

# This program does not crash.
# Outputs: "Got an exception, but I'm responding intelligently!"


The exception still happens, but it doesn’t cause the program to crash because it was “rescued.” Instead of exiting, Ruby runs the code in the rescue block, which prints out a message. This is nice, but it has one big limitation. It tells us “something went wrong,” without letting us know what went wrong.

Exception Objects


All of the information about what went wrong is going to be contained in an exception object.

begin
1/0
rescue => e
puts "#{e.message}"
end

# Rescues all errors, an puts the exception object in `e`
rescue => e

# Rescues only ZeroDivisionError and puts the exception object in `e`
rescue ZeroDivisionError => e


begin
 # Any exceptions in here...
 1/0
rescue ZeroDivisionError => e
  puts "Exception Class: #{e.class.name}"
  puts"Exception Message:#{e.message}"
  put"Exception Backtrace:#{e.backtrace}"
end

# Outputs:
# Exception Class: ZeroDivisionError
# Exception Message: divided by 0
# Exception Backtrace: ...backtrace as an array...

Most exception objects will provide you with at least three pieces of data:
1. The type of exception, given by the class name.
2. An exception message
3. A backtrace

All of the information about what went wrong is going to be contained in an
exception object.


begin
 # Any exceptions in here...
 1/0
rescue ZeroDivisionError => e
  puts "Exception Class: #{e.class.name}"
  puts"Exception Message:#{e.message}"
  put"Exception Backtrace:#{e.backtrace}"
end

# Outputs:
# Exception Class: ZeroDivisionError
# Exception Message: divided by 0
# Exception Backtrace: ...backtrace as an array...


Most exception objects will provide you with at least three pieces of data:
1.The type of exception, given by the class name.
2.An exception message
3.A backtrace


Raising Your Own Exceptions

So far we’ve only talked about rescuing exceptions. You can also trigger your own exceptions. This process is called “raising” and you do it by calling the raise method.

begin
  # raises an ArgumentError with the message "you messed up!"
  raise ArgumentError.new("You messed up!")
rescue ArgumentError => e
  puts e.message
end

This being Ruby, raise can be called in several ways:

# This is my favorite because it's so explicit
  raise RuntimeError.new("You messed up!")

# ...produces the same result
  raise RuntimeError, "You messed up!"

# ...produces the same result. But you can only raise
# RuntimeErrors this way
  raise "You messed up!"

Making Custom Exceptions

Ruby’s built-in exceptions are great, but they don’t cover every possible use case.

To make a custom exception, just create a new class that inherits from StandardError.

class PermissionDeniedError < StandardError
end

raise PermissionDeniedError.new()


class PermissionDeniedError < StandardError
attr_reader :action
def initialize(message, action)
# Call the parent's constructor to set the message
super(message)
# Store the action in an instance variable
@action = action
end
end

# Then, when the user tries to delete something they don't
# have permission to delete, you might do something like this:
raise PermissionDeniedError.new("Permission Denied",:delete)

The  Class  Hierarchy


We just made a custom exception by subclassing StandardError, which itself subclasses Exception.

In fact,  if you look at  the  class hierarchy  of any  exception  in Ruby,  you’ll find it eventually  leads back to Exception.  Here, I’ll prove it to you. These are most of Ruby’s built-in  exceptions, displayed hierarchically:

Exception
   NoMemoryError
   ScriptError
       LoadError
       NotImplementedError
       SyntaxError
    SecurityError
    SignalException
        Interrupt
     StandardError
        ArgumentError
        UncaughtThrowError
        EncodingError
        CompatibilityError
        ConverterNotFoundError
        InvalidByteSequenceError
        UndefinedConversionError
        FiberError
        IOError
           EOFError
        IndexError
        KeyError
        StopIteration
        LocalJumpError
        NameError
           NoMethodError
        RangeError
           FloatDomainError
        RegexpError
        RuntimeError
        SystemCallError
        ThreadError
        TypeError
        ZeroDivisionError
SystemExit
SystemStackError
fatal – impossible to rescue

Rescuing errors of a specific class also rescues errors of its child classes.For example, when you rescue StandardError , you not only rescue exceptions with class StandardError but those of its children as well. If you look at the chart, you’ll see this includes ArgumentError,IOError, and many more.

begin
 #do something
rescue Exception => e
end

Rescuing All Exceptions (The Wrong Way)

begin
 #do something
rescue Exception => e
end

The code above will rescue every exception.Don’t do it! It’ll break your program in weird ways.

That’s because Ruby uses exceptions for things other than errors. It also uses them to handle messages from the operating system called “Signals.” If you’ve ever pressed “ctrl-c” to exit a program, you’ve used a signal. By suppressing all exceptions, you also suppress those signals.

There are also some kinds of exceptions — like syntax errors — that really should cause your program to crash. If you suppress them, you’ll never know when you make typos or other mistakes.


Rescuing All Errors (The Right Way)


Go back and look at the class hierarchy chart and you’ll see that all of the errors you’d want to rescue are children of StandardError.

That means that if you want to rescue “all errors” you should rescue StandardError.

begin
 do_something
rescue StandardError => e
 # Only your app's exceptions are swallowed. Things like SyntaxError are left alone.
end

In fact, if you don’t specify an exception class, Ruby assumes you mean StandardError

begin
  do_something
rescue => e
  # This is the same as rescuing StandardError
end


Advanced Rescue & Raise

Full Rescue Syntax

you have a situation that requires a more sophisticated approach to rescue an exception. Below is an example of Ruby’s full rescue syntax.

begin
 do_someting
rescue TooHotError => too_hot
 # This code is run if a TooHotError occurs
rescue TooColdError => too_cold
 # This code is run if a TooColdError occurs
else
 # This code is run if no exception occurred at all
ensure
 # This code is always run, regardless of whether an exception occurred
end

• else - is executed when no exceptions occur at all.
• ensure - is always executed, even if exceptions did occur. This is really
   useful for actions like closing files when something goes wrong.
• rescue - you know what rescue, is, but I just wanted to point out that
   we’re usingmultiple rescues to provide different behavior for different
   exceptions.

 begin
request_web_page
 rescue TimeoutError
  retry_request
 rescue
send_alert
 else
record_success
 ensure
close_network_connection
 else
 
Here, we respond to timeout exceptions by retrying. All other exceptions trig-
ger alerts. If no error occurred, we save the success in the database. Finally,
regardless of what else occurred, we always close the network connection.









Tuesday, 9 August 2016

Active Jobs

Active job is a rails framework for running background jobs, It's included as rails component as same like other components like active record, Active model etc

What is Background Jobs and why do we need?
You’re always striving to give your users a better experience when they use your website or application, 

One of the most important ways to achieve this is by giving them quick server response times and processing the non web responses in the background like Email, Payments, sms, Data processing, Video, audio upload etc..


  • Active Job was first included in Rails 4.2
  • Why to use Active Job instead of directly using Third party Background processing
  • Gives the common place to write the jobs
  • We will be able to switch between the queuing backend without having to rewrite the jobs just by changing the queue and backend processing table.
  • Active Job allows your Rails app to work with any one of the backend queue through a single standard interface

  • Even if you aren’t ready to use a queue in your application, you can still use Active Job with the default Active Job Inline backend Jobs enqueued with the Inline adapter get executed immediately.

Active Job adapters Backends Features


|                   | Async | Queues | Delayed    | Priorities | Timeout | Retries |
|-------------------|-------|--------|------------|------------|---------|---------|
| Backburner        | Yes   | Yes    | Yes        | Yes        | Job     | Global  |
| Delayed Job       | Yes   | Yes    | Yes        | Job        | Global  | Global  |
| Qu                | Yes   | Yes    | No         | No         | No      | Global  |
| Que               | Yes   | Yes    | Yes        | Job        | No      | Job     |
| queue_classic     | Yes   | Yes    | Yes*       | No         | No      | No      |
| Resque            | Yes   | Yes    | Yes (Gem)  | Queue      | Global  | Yes     |
| Sidekiq           | Yes   | Yes    | Yes        | Queue      | No      | Job     |
| Sneakers          | Yes   | Yes    | No         | Queue      | Queue   | No      |
| Sucker Punch      | Yes   | Yes    | Yes        | No         | No      | No      |
| Active Job Async  | Yes   | Yes    | Yes        | No         | No      | No      |
| Active Job Inline | No    | Yes    | N/A        | N/A        | N/A     | N/A     |

Resque and delayed Job

  1. Resque supports multiple queues
  2. DelayedJob supports numeric priorities
  3. Resque workers are resilient to memory leaks
  4. DelayedJob workers are extremely simple and easy to modify
  5. Resque requires Redis
  6. DelayedJob requires ActiveRecord
  7. Resque can only place JSONable Ruby objects on a queue as arguments
  8. DelayedJob can place any Ruby object on its queue as arguments
  9. Resque includes a Sinatra app for monitoring what's going on
  10. DelayedJob can be queried from within your Rails app if you want to add an interface

A. Generating a job
     Active Job provides a Rails generator to create jobs
     rails generate job site_subscription_payment
B. Enqueue the Job
    SiteSubscriptionPaymentJob.perform_later subscription_obj
    SiteSubscriptionPaymentJob.set(wait_until:         Date.tomorrow.noon).perform_later(subscription_obj)
    SiteSubscriptionPaymentJob.set(wait: 1.week).perform_later(subscription_obj)
    SiteSubscriptionPaymentJob.perform_later(subscription_obj, company)
C. Job Execution
For enqueuing and executing jobs in production we need to set up a queuing backend Rails itself only provides an in-process queuing system, which only keeps the jobs in RAM. If the process crashes or the machine is reset, then all outstanding jobs are lost with the default async back-end
D. Setting the Backend  config/application.rb
config.active_job.queue_adapter = :delayed_job
E. Starting the Backend
Since jobs run in parallel to your Rails application, most queuing libraries require that you start a library-specific queuing service (in addition to starting your Rails app) for the job processing to work
F. Queues
MyJob.set(queue: :another_queue).perform_later(record)
queue_as :low_priority
Callbacks

Active Job provides hooks during the life cycle of a job. Callbacks allow you to trigger logic during the life cycle of a job.

A. Available callbacks
before_enqueue
around_enqueue
after_enqueue
before_perform
around_perform
after_perform

 before_enqueue do |job|
    # Do something with the job instance
  end

  around_perform do |job, block|
    # Do something before perform
    block.call
    # Do something after perform
  end

Action Mailer
One of the most common jobs in a modern web application is sending emails outside of the request-response cycle
So the user doesn't have to wait on it. Active Job is integrated with Action Mailer so you can easily send emails asynchronously

# If you want to send the email now use #deliver_now
ApplicationNotifier.user_approved(@user).deliver_now

# If you want to send the email through Active Job use #deliver_later
ApplicationNotifier.user_approved(@user).deliver_later






Tuesday, 2 February 2016

Automation Testing Using Rspec and Cucumber In Ruby on Rails

Automation Testing:

1. Unit Test

A unit test focuses on a single “unit of code” – usually a function in an object or module. By making the test specific to a single function, the test should be simple, quick to write, and quick to run. This means you can have many unit tests, and more unit tests means more bugs caught. They are especially helpful if you need to change your code, as you can safely do so and trust that any other code will not break.

2. Integration Test

Multiple pieces are tested together, for example testing database access code against a test database

3. Acceptance test/ Function Test/Automation Test

Automatic testing of the entire application End to End Testing or "Full Application", for example using a tool like Selenium to automatically run a browser.

TDD - Test Driven Development

a. Write Test
b. Write code
c. Run Test
d. Clean up code

Red, Green, Refactor

BDD - Behavior Driven Development

Difference Between TDD and BDD

BDD uses a more verbose style so that it can be read almost like a sentence. BDD is to test the TDD

  1. BDD focuses on the behavioural aspect of the system rather than the implementation aspect of the system that TDD focuses on.
  2. BDD gives a clearer understanding as to what the system should do from the perspective of the developer and the customer. TDD only gives the developer an understanding of what the system should do.
  3. BDD allows both the developer and the customer to work together to on requirements analysis that is contained within the source code of the system.

Webdriver

WebDriver is a tool for writing automated tests of websites. It aims to mimic the behaviour of a real user, and as such interacts with the HTML of the application.

Capybara uses the same DSL to drive a variety of browser and headless drivers
Rack_test
RackTest is Capybara's default driver.
It is written in pure Ruby and does not have any support for executing JavaScript.
Since the RackTest driver interacts directly with Rack interfaces, it does not require a server to be started
If your application is not a Rack application (Rails, Sinatra and most other Ruby frameworks are Rack applications) then you cannot use this driver
you cannot use the RackTest driver to test a remote application, or to access remote URLs (e.g., redirects to external sites, external APIs, or OAuth services)

Selenium
Capybara-webkit
Poltergeist

Rspec

Rspec is a Testing Framework, Rspec stands for Ruby Specification. Rspec is a low level testing, Rspec is very good for unit testing, that is testing models, controllers, views.


Add below code into your gemfile and bundle install or install it by command line
group :development, :test do
  gem 'rspec-rails', '~> 2.0'
end
Or  gem install rspec-rails

Create the Basic Skelton
rails generate rspec:install

Create the RSpec binstub. In short, the binstub will allow you to run RSpec with bin/rspec instead of bundle exec rspec
bundle binstubs rspec-core

Cucumber 
Cucumber is a high-level testing framework which is designed to let you use Behaviour Driven Development (BDD) to create Ruby on Rails applications
Cucumber’s unique feature is that it uses English (or a number of other supported languages) to define an application’s behaviour.
Gherkin is the language that Cucumber understands
It is a Business Readable, Domain Specific Language that lets you describe software’s behaviour withIt Uses the struout detailing how that behaviour is implemented

Feature file consists of the scenario
Step definition consists of the ruby code to pass the scenario


shoulda-matchers

shoulda-matchers lets us spec common Rails functionality, like validations and associations, with less code.
gem 'shoulda-matchers'
bundle install
should validate_presence_of(:firstname)
http://matchers.shoulda.io/docs/v3.1.1/




Factory-Girl

factory_girl is a fixtures replacement with a straightforward definition syntax(i.e Test data)
gem 'factory_girl' and bundle install
Create the directory called factories and define with the filename same as table name
FactoryGirl.define do
  factory :user do
    firstname "satheesh"
    lastname "kumar"
    email "satheeshkumark@gmail.com"
    password "password"
  end
end

@user = FactoryGirl.build(:user)

Thursday, 3 July 2014

What's the difference between PayPal Standard, Express, Pro, and Advanced?

Paypal offers integrations with four types of PayPal: Standard, Express, Pro, and now Advanced.

PayPal Standard is the basic type of PayPal. When this is enabled, the customer will have to fill out your store checkout and will be able to choose PayPal Standard in the Payment section. When they are sent to PayPal, they will be able to log in to their PayPal account or use a credit/debit card without having an account. The line items will be displayed on PayPal and the order will be submitted on their end, not your store's.

PayPal Express requires the customer to have a PayPal account. When you enable this, it will display on both the View Cart page (as a button) and on the Checkout page (as a choice in the Payment section). When the customer is sent to PayPal, the line items will not be shown. The customer will be sent back to the store to choose their shipping method and will submit the order from the store's checkout page.

PayPal Pro is considered a payment gateway. You would enable this is in the Credit Cards section of your Payment Settings. You would use this to accept credit cards on your site, and the customer would not know that PayPal is being used. When you set this up, you can either use the API signature or certificate. If you are going to also use PayPal Express, you will need to use the certificate.

PayPal Advanced is the newest type of PayPal integration. With PayPal Advanced, you can accept both PayPal and credit cards on your site. You can set it so that customers are sent to PayPal to pay, or you can give them the ability to pay with a credit card without ever having to leave your site. This type of PayPal will work with all other PayPal types, and since it's not a payment gateway itself, you can have it enabled alongside a true payment gateway like Authorize.net.

Wednesday, 2 July 2014

Steps to resolve Heartbleed Vulnerability

Check your server openssl Version

openssl version

Verify this version is vulnerable in openssl.com or Check through the following tools


If your server is affected take immediate action

Update your openssl and libssl version

sudo apt-get install --only-upgrade openssl
sudo apt-get install --only-upgrade libssl1.0.0


Restart all the services that are depends on openssl and libssl(ex: apache2,postgresql.sendmail etc..)

Reissue your ssl certificate through following steps

Create new private key and csr. 

openssl genrsa -des3 -out /etc/ssl/private/privatekeyfilename.key

openssl req -new -key /etc/ssl/private/privatekeyfilename.key -out /etc/ssl/certs/outputfilename.csr


Then send this to your ssl provider to reissue the ssl certificate.

Once you received the ssl certificate from your ssl provider install it in your server.

Request to all your user to change their password.

Now you and your user will be safe!!!




Wednesday, 12 February 2014

Difference between Ruby Require VS Load VS Include VS Extend

When you Include a module into your class as shown below, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your code to avoid duplication, for instance, if there were multiple classes that would need the same code within the module.
The following assumes that the module Log and class TestClass are defined in the same .rb file. If they were in separate files, then ‘load’ or ‘require’ must be used to let the class know about the module you’ve defined.
module Log
  def class_type
    "This class is of type: #{self.class}"
  end
end
 
class TestClass
  include Log
  # ...
end
 
tc = TestClass.new.class_type
The above will print “This class is of type: TestClass”
The load method is almost like the require method except it doesn’t keep track of whether or not that library has been loaded. So it’s possible to load a library multiple times and also when using the load method you must specify the “.rb” extension of the library file name.
Most of the time, you’ll want to use require instead of load but load is there if you want a library to be loaded each time load is called. For example, if your module changes its state frequently, you may want to use load to pick up those changes within classes loaded from.
Here’s an example of how to use load. Place the load method at the very top of your “.rb” file. Also the load method takes a path to the file as an argument:
load 'test_library.rb'
So for example, if the module is defined in a separate .rb file than it’s used, then you can use the
File: log.rb
module Log
  def class_type
    "This class is of type: #{self.class}"
  end
end
File: test.rb
load 'log.rb'
 
class TestClass
  include Log
  # ...
end
The require method allows you to load a library and prevents it from being loaded more than once. The require method will return ‘false’ if you try to load the same library after the first time. The require method only needs to be used if library you are loading is defined in a separate file, which is usually the case.
So it keeps track of whether that library was already loaded or not. You also don’t need to specify the “.rb” extension of the library file name.
Here’s an example of how to use require. Place the require method at the very top of your “.rb” file:
require 'test_library'
When using the extend method instead of include, you are adding the module’s methods as class methods instead of as instance methods.
Here is an example of how to use the extend method:
module Log
  def class_type
    "This class is of type: #{self.class}"
  end
end
 
class TestClass
  extend Log
  # ...
end
 
tc = TestClass.class_type
The above will print “This class is of type: TestClass”
When using extend instead of include within the class, if you try to instantiate TestClass and call method class_type on it, as you did in the Include example above, you’ll get a NoMethodError. So, again, the module’s methods become available as class methods.