Thursday, 28 May 2015

List of Common mistakes in Ruby



Always use spaces around operators, after commas, colons and semicolons, around { and before }. White space might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code. Also it makes the design more readable and code much cleaner.

product = 1 * 2
array = [1, 2, 3, 4, 5]
array.map { |a| a + 2 }


There should be no spaces after (, [ or before ], ) these brackets.

['ankur', 'vyas']
sum(a, b)

Also don't use spaces in while providing the range.

Use 5..9 over 5 .. 9
Use 'a'..'z' over 'a' .. 'z'

When using switch case statements use the following indentation.

case
  when input = '+'
    puts 'The operation is addition'
  when '-'
    puts 'The operation is subtraction'
  when '*'
    puts 'The operation is multiplication'
  else
    puts 'The operation is division'
end

Use following indentation if the parameters exceeds to more than one line.

def send_mail(source)
  Mailer.deliver( to: 'ankurvy1@gmail.com',
                  from: 'someone@someone.com',
                  subject: 'Message subject',
                  body: source.text)
end

Use splat for better assignments.

element_1, *other_elements = ['a', 'n', 'k', 'u', 'r']

If only 2 conditions are present use the ternary operators.

var_1 = condition ? assignment_1 : assignment_2


If you are setting a variable using the if condition the use following syntax.

variable_result = if condition_1
                    a
                  else_if condition_2
                    b
                  else
                    c
                  end

Avoid return statements at the end of the line. In ruby the last line of the method is returned.

Use snake case for all the ruby variables.

variable_1, some_variable

Use camel case for class names.

ClassOne, ClassTwo

Use screaming snake case for the constants' names.

CONSTANT_1, CONSTANT_2


Use %w for the string arrays and %i for the symbol arrays.

STATUS_MAP = %w(open closed draft paid)
SYMBOL_MAP = %i(symbol1 symbol2 symbol3)

Use interpolation over concatenation.

Use "#{string_1} < #{string2} >" over string_1 + '<' + string2 + '>'

Assign single quotes to the string which does not have interpolation.

Use 'string 1' over "string 1"

Do not use the word partial when you don't want to pass some variables in it.

Use render 'partial_1' over render partial: 'partial_1'


Reference:



Saturday, 23 May 2015

Scope and Access modifiers in Ruby


Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members.

Access modifiers set the visibility of methods and member fields. Ruby has three access modifiers: public, protected and private. In Ruby, all data members are private. Access modifiers can be used only on methods. Ruby methods are public, unless we say otherwise. The scope of the methods is until another scope comes i.e. when we write private all the methods below it are private until any other scope (i.e. protected or public).

NOTE: Ruby does not apply any access control over instance and class variables.

Public Methods: Public methods can be called by anyone. Methods are public by default except for initialize, which is always private.

Private Methods: Private methods cannot be accessed, or even viewed from outside the class. Only the class methods can access private members.

Protected Methods: A protected method can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.

  • The public methods can be accessed from inside the definition of the class as well as from the outside of the class.
  • The difference between the protected and the private methods is subtle. Neither can be accessed outside the definition of the class.
  • They can be accessed only within the class itself and by inherited or parent classes.

Example:

# define a class
class Box
# constructor method
def initialize(w,h)
 @width, @height = w, h
end

# instance method by default it is public
def getArea
 getWidth * getHeight
end

# define private accessor methods
private

def getWidth
 @width
end

def getHeight
 @height
end

protected

def printArea
 @area = getWidth * getHeight
 puts "Big box area is : #@area"
end
end

# create an object
box = Box.new(10, 20)

# call instance methods
a = box.getArea
puts "Area of the box is : #{a}"

#try to call private methods
w = box.getWidth

puts "Width of the box is : #{w}"

# try to call protected or methods
box.printArea

OUTPUT:

Area of the box is : 200

access_modifiers.rb:39:in `<main>': private method `getWidth' called for #<Box:0x93ee654 @width=10, @height=20> (NoMethodError)


References:





Ruby Mixins


What’s a Mixin?

A mixin can basically be thought of as a set of code that can be added to one or more classes to add additional capabilities without using inheritance. In Ruby, a mixin is code wrapped up in a module that a class can include or extend. In fact, a single class can have many mixins.

When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.

Ruby does not support multiple inheritance directly but Ruby Modules have another wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.

module A
  def a1
  end
  def a2
  end
end
module B
  def b1
  end
  def b2
  end
end

class Sample
include A
include B
  def s1
  end
end

samp=Sample.new
samp.a1 # From module A
samp.a2 # From module A
samp.b1 # From module B
samp.b2 # From module B
samp.s1 # Instance method


In the example above, the object of the class Sample is able to call the methods of the module A as well as module B. Hence, we get the multiple inheritance.

Include vs Extend

Modules can either be included or extended depending on whether the methods will be added as instance methods or class methods, respectively.

# Include the Module
module Calculator
 def add(x,y)
   x + y
 end
end
class A
 include Calculator
 def calculate
   add(2,3)
 end
end

p = A.new
puts p.calculate # Puts 5


In the example above a Calculator module is defined which sums up two integers via the add method. The A class includes the Calculator module which will add its methods as instance methods to the A class. It’s worth noting that everything defined in the module is added to the class including methods (public, protected, private), attributes (e.g. attr_accessor :name) and constants.


If instead we wanted to provide a add via a class method I’d use the extend method as shown below.

# Extend the Module
module Calculator
 def add(x,y)
   x + y
 end
end
class A
 extend Calculator
end

puts A.add(4,5) # Puts 9


It’s also possible to mixin a module to a single instance at runtime as shown in the following example.

# Extending the Module at the runtime
class B; end
b = B.new
b.extend Calculator
puts b.add(5,2)


Another common pattern is to define a module that will mixin instance and class methods.

module AcmeModel
 def self.included(base)
    base.extend(ClassMethods)
 end

 def brand
    "acme"
 end

 module ClassMethods
    def all
     # get all of the AcmeModel instances
     []
    end
 end
end

class Widget
 include AcmeModel
end

w = Widget.new
w.brand # "acme" is the output,
Widget.all  # invoke the class method that was added


In this example the AcmeModel provides an instance method named brand. More importantly it overrides the included class method, provided by the Module class. The included method is a callback that gets invoked whenever the module is included by antoher class or module. At that point we extend the class that included the AcmeModel, the Widget class in this example, with the ClassMethods module.

Lastly, you should also know that your module can override the extended class method which acts as callback when the module is extended.

References: