Skip to content
This repository has been archived by the owner. It is now read-only.

Ruby on Rails Cheat Sheet

respinos edited this page Nov 23, 2015 · 2 revisions

(1) Include vs Extend

  • include : mixes in specified module methods as instance methods in the target class
  • extend : mixes in specified module methods as class methods in the target class
module ReusableModule
  def module_method
    puts "Module Method: Hi there!"
  end
end

class ClassThatIncludes
  include ReusableModule
end
class ClassThatExtends
  extend ReusableModule
end

puts "Include"
ClassThatIncludes.new.module_method       # "Module Method: Hi there!"
puts "Extend"
ClassThatExtends.module_method            # "Module Method: Hi there!"

Now, if you have an object you can do

obj = ClassThatIncludes.new.module_method
obj.extend SeusableModule

Now you can do:

obj.moudle_method,

However, modules very often override include's behavior by monkey-patching the included method. This is very prominent in legacy Rails code. more details from Yehuda Katz. This is sometimes called metaprogramming.

Monkey patching is when you replace methods of a class at runtime? Here is an example:

This adds class method to String ( core class )

class String
  def self.jose
    "This is so much fun."
  end
end

You can now use this method on the String class like this:

String.jose
=> "This is so much fun."

However, not only can we added methods to the core String class, we can also modify the behaviour of existing methods!

class String
  def upcase
    self.reverse
  end
end

In this example we’re hijacking the upcase method and calling the reverse method instead!

"hello".upcase
=> "olleh"

So as you can see, it’s incredibly easy to add or modify methods on an existing class, even when you don’t own that class or it is part of the core of Ruby.

(2) autoload - what does this do.

autoload works in a similar way to require, but it only loads the file specified when a constant of your choosing is accessed/used for the first time

Let's say you have a file called mylibrary.rb containing the following code:

puts "I was loaded!"

class MyLibrary
end

Now, from irb, let's use require to load the "library":

irb(main):001:0> require 'mylibrary'
I was loaded!
=> true

Because require works straight away, the puts method gets executed immediately. So let's restart irb and see what happens if we use autoload instead:

irb(main):001:0> autoload :MyLibrary, 'mylibrary'
=> nil
irb(main):002:0> MyLibrary.new
I was loaded!
=> #<MyLibrary:0x0b1jef>

So in Hydra.....

(3) include do ... end

What is this, and what does it do?

It has to be used with

module Named
  extend ActiveSupport::Concern

Note these two are the same:

my_obj = Object.new
my_obj.extend MyMod

my_obj = Object.new
my_obj.singleton_class.class_eval do
  include MyMod
end