Wednesday 22 June 2016

Ruby Load Path and Auto Loading in Rails - Other small concepts





Hi Readers,

This is the last post for Ruby beginners. Today we are going to learn some small concepts and Ruby load paths and auto loading in Rails

define_method:

class Array 
  {:second => 1, :third => 2}.each do |method,element| 
    define_method(method) do 
      self[element] 
    end 
  end 
end 
 
array = %w(A B C) 
puts array.first # => A 
puts array.second # => B 
puts array.third # => C  

Object Space:

    ObjectSpace.each_object(Numeric) { |n| puts n }   

Class Reflection:

    # Using Class#superclass 
    klass = Fixnum 
    begin 
      print klass 
      klass = klass.superclass 
      print " < " if klass 
    end while klass 
    # => Fixnum < Integer < Numeric < Object 
     
    # Using Class#ancestors 
    Fixnum.ancestors 
    # => Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel 
     
    # Inspecting methods and variables 
    Fixnum.public_instance_methods(false) 
    Fixnum.class_variables 
    Fixnum.constants 
    1.instance_variables

System Hooks: Class#inherited

    class A 
      @@subclasses = {}   
      # Invoked when a new class is created that extends this class 
      def self.inherited(child) 
        puts "inherited" 
        @@subclasses[self] ||= [] 
        @@subclasses[self] << child 
      end 
       
      def self.subclasses 
        @@subclasses[self] 
      end 
    end 
     
    class B < A 
    end 
     
    puts A.subclasses   

Ruby Load Path and Auto Loading in Rails:

  • The Ruby load path is stored in $: and is used when you require code
  • Models, views, controllers, and helpers under the app dir are loaded automatically
  • Classes under lib are also loaded automatically
  • You can add load paths in config/environment.rb
  • Class and module names must correspond to the file path where they are defined for auto loading to work


Tuesday 14 June 2016

const_missing – for Auto Loading Classes, eval and binding

Hi Readers,

Today we are going to learn that if any class is not defined, even though you are trying to create object for that non existing class, then ruby raises an exception called "constant_missing".

const_missing – for Auto Loading Classes:

    def Object.const_missing(name)  
      @looked_for ||= {}  
      str_name = name.to_s  
      raise "Class not found: #{name}" if @looked_for[str_name]  
      @looked_for[str_name] = 1  
      file = str_name.downcase  
      require file  
      klass = const_get(name)  
      return klass if klass  
      raise "Class not found: #{name}"  
    end  

eval and binding:

def evaluate_code(code, binding) 
  a = 2 
  eval code, binding 
end 
 
a = 1 
evaluate_code("puts a", binding) # => 1

instance_eval:

    require 'person_class'  
    andreas = Person.new("Andreas")  
    puts andreas.instance_eval { @name } # => Andreas  

class_eval and module_eval:

    class Person 
      def self.add_method(method) 
        class_eval %Q{ 
          def #{method} 
            puts "method #{method} invoked" 
          end 
        } 
      end     
     
      add_method(:say_hi) 
    end 
     
    Person.new.say_hi   


Thank for reading it, hope you will practice and get some idea.




Monday 13 June 2016

method_missing: A VCR and Using the VCR


Hi Readers,

Today we are going to take an example class VCR and verify the method_missing concept.

method_missing: A VCR

    class VCR 
      def initialize 
        @messages = [] 
      end 
     
      def method_missing(method, *args, &block) 
        @messages << [method, args, block] 
      end 
     
      def play_back_to(obj) 
        @messages.each do |method, args, block| 
          obj.send(method, *args, &block) 
        end 
      end 
    end

Using the VCR:

    require 'vcr' 
     
    vcr = VCR.new 
    vcr.gsub! /Ruby/, "Crazy" 
    vcr.upcase! 
    object = "I Go Ruby" 
    vcr.play_back_to(object) 
    puts object  


Just practice this example , i will get back to you with new concept.

Thanks for reading, subscribe this blog to get more updates.

Friday 10 June 2016

Open Class Definitions and Method Aliasing


Hi readers,

In this post we are going to learn how to open existing class defination and alias the method which is exist already in the class.

Open Class Definitions and Method Aliasing:

    class Peter 
      def say_hi 
        puts "Hi" 
      end 
    end 
     
    class Peter 
      alias_method :say_hi_orig, :say_hi 
      def say_hi 
        puts "Before say hi" 
        say_hi_orig 
        puts "After say hi" 
      end 
    end 
     
    Peter.new.say_hi  

Core Classes are Also Open:

 class Integer
  def even?
    (self % 2) == 0
  end
end
 
p (1..10).select { |n| n.even? } # => [2, 4, 6, 8, 10] 

Hope you understand the concept and you will practice this.
Thanks for reading this, if like share this.

Wednesday 8 June 2016

RDoc and Option Parsing - Ruby on the Command Line

Hi Readers,

Today we are going to learn RDoc and Option Parsing, means ruby documentation and their options. In this we are also using ruby in command line.

RDoc and Option Parsing:

#!/usr/bin/env ruby 
# == Synopsis 
# This script takes photographs living locally on my desktop or laptop 
# and publishes them to my homepage at http://marklunds.com. 

# == Usage 

# Copy config file publish-photos.yml.template to publish-photos.yml and edit as appropriate. 
# ruby publish-photos [ -h | --help ] <photo_dir1> ... <photo_dirN> 
 
# Load the Rails environment 
require File.dirname(__FILE__) + '/../config/environment' 
require 'optparse' 
require 'rdoc/usage' 
 
opts = OptionParser.new 
opts.on("-h", "--help") { RDoc::usage('usage') } 
opts.on("-q", "--quiet") { Log::Logger.verbose = false } 
opts.parse!(ARGV) rescue RDoc::usage('usage')   

Ruby on the Command Line:

# Query and replace 
ruby -pi.bak -e "gsub(/Perl/, 'Ruby')" *.txt 
 
# Grep 
ruby -n -e "print if /Ruby/" *.txt 
ruby -e "puts ARGF.grep(/Ruby/)" *.txt

Hope you will get this concepts.
Share this page. Place comment on it.

Tuesday 7 June 2016

Dup method, Regular expressions and invoking external programs

The dup Method and Method Arguments:

    # Methods that change their receiver end with an exclamation mark by convention. 
    # If you need to invoke an exclamation mark method on a method argument and you want 
    # to avoid the object from being changed, you can duplicate the object first 
    # with the Object#dup method. Core classes such as String, Hash, and Array all have 
    # meaningful implementations of the dup method. Here is an example from Rails: 
     
    class ActiveRecord::Base 
      def attributes=(new_attributes) 
        return if new_attributes.nil? 
        attributes = new_attributes.dup # duplicate argument to avoid changing it 
        attributes.stringify_keys! # modify the duplicated object 
        # ... method continues here 
      end 
    end   

Regular Expressions:

    "Ruby" =~ /^(ruby|python)$/i 
    "Go\nRuby" =~ /Go\s+(\w+)/m; $1 == "Ruby" 
    "I Go Ruby" =~ /go/i; $& == "Go"; $` == "I "; $' == " Ruby"
    pattern = "."; Regexp.new(Regexp.escape(pattern))
    "I Go Ruby"[/(go)/i, 1] == "Go"
    puts "I Go Ruby".gsub(%r{Ruby}, '\0 or I go bananas') 
    "I Go Ruby".gsub(/ruby/i) { |lang| lang.upcase } 
    line = "I Go Ruby" 
    m, who, verb, what = *line.match(/^(\w+)\s+(\w+)\s+(\w+)$/) 
    # \s, \d, [0-9], \w - space, digit, and word character classes 
    # ?, *, +, {m, n}, {m,}, {m} - repetition   

Invoking External Programs:

    system("ls -l") 
    # $? is a predefined variable with the exit status 
    puts $?.exitstatus if !$?.success? 
    # The back ticks "`" return the output of the external program 
    standard_out = `ls -l`   


Hope you understand the concepts.

if like
   share
else
   comment
end

Thank You

Monday 6 June 2016

Case statements, Blocks and String operations

Hi Readers,

Today we are going to learn how to write case statements in Ruby. Know about ruby blocks and some string operations with examples.

Case:

    x = 11 
    case x 
    when 0 
    when 1, 2..5 
      puts "Second branch" 
    when 6..10 
      puts "Third branch" 
    when *[11, 12] 
      puts "Fourth branch" 
    when String: puts "Fifth branch" 
    when /\d+\.\d+/ 
      puts "Sixth branch" 
    when x.to_s.downcase == "peter" 
      puts "Seventh branch" 
    else 
      puts "Eight branch" 
    end   

Blocks - Usage examples:

    # Iteration 
    [1, 2, 3].each { |item| puts item } 
     
    # Resource Management 
    File.open("file.txt", "w") do |file| 
      file.puts "foobar" 
    end 
     
    # Callbacks 
    widget.on_button_press do 
      puts "Got button press" 
    end 
     
    # Convention: one-line blocks use {...} and multiline 
    # blocks use do...end  

Common String Operations:

    "  ".empty? == true 
    IO.read(__FILE__).each_with_index { |line, i| puts "#{i}: #{line}" } 
    "abc".scan(/./).each { |char| char.upcase } 
    "we split words".split.join(", ") 
    "    strip space   ".strip 
    sprintf("value of %s is %.2f", "PI", 3.1416) 
    "I Go Ruby"[2, 2] == "I Go Ruby"[2..3] # => "Go"   

Hope you will understand this concepts. Next we will meet with different concept.
Please practice these to get hands on experience.

Share if you like else comment.

Ruby Conditional statements and Iterators

Hi Readers,

In this we are going to learn conditions and Iterators in Ruby. Please follow the below concepts.

if, unless, and the ? Operator

message = if count > 10 
            "Try again" 
          elsif tries == 3 
            "You lose" 
          else 
            "Enter command" 
          end 
 
raise "Unauthorized" if !current_user.admin? 
raise "Unauthorized" unless current_user.admin? 
 
status = input > 10 ? "Number too big" : "ok"  

Iterators: while, until, for, break, and next

while count < 100 
  puts count 
  count += 1 
end 
 
payment.make_request while (payment.failure? and payment.tries < 3) 
 
for user in @users 
  next if user.admin? 
  if user.paid? 
    break 
  end 
end 
 
until count > 5 
  puts count 
  count += 1 
end   


Practice with different conditions,
Please share this to help others.

 


Ruby Range class, Structs and Exceptions

Hi readers,

In this post we are going to know about Range class, Structs in ruby and exceptions.

Range Class:

    # Two dots is inclusive, i.e. 1 to 5 
    (1..5).each { |x| puts x**2 }  
     
    # Three dots excludes the last item, i.e. 1 to 4 
    (1...5).each { |x| puts x } 
     
    (1..3).to_a == [1, 2, 3]  

Structs:

    Rating = Struct.new(:name, :ratings)  
    rating = Rating.new("Rails", [ 10, 10, 9.5, 10 ])  
     
    puts rating.name 
    puts rating.ratings  

Exceptions:

    begin  
      raise(ArgumentError, "No file_name provided") if !file_name 
      content = load_blog_data(file_name) 
      raise "Content is nil" if !content  
    rescue BlogDataNotFound  
      STDERR.puts "File #{file_name} not found"  
    rescue BlogDataConnectError 
      @connect_tries ||= 1 
      @connect_tries += 1 
      retry if @connect_tries < 3  
      STDERR.puts "Invalid blog data in #{file_name}"  
    rescue Exception => exc  
      STDERR.puts "Error loading #{file_name}: #{exc.message}" 
      raise 
    end  


Just can you practice above examples, then you will understand the concept, otherwise place comment on it.

Thank you share with your friends.

Ruby Symbols And More about Methods

Ruby Symbols:

# Symbols start with a colon 
:action.class == Symbol 
:action.to_s == "action" 
:action == "action".to_sym 
 
# There is only one instance of every symbol 
:action.equal?(:action) # => true 
'action'.equal?('action') # => false 
 
# Symbols are typically used as keys in hashes 
my_hash = {:controller => "home", :action => "index"} 

More about Methods:

  • Arbitrary number of arguments: def my_methods(*args)
  • Converting Array to arguments: my_method([a, b]*)
  • Dynamic method invocation: object.send(:method_name)
  • Duck typing: object.respond_to?(:method_name)
  • If the last argument is a Hash, the braces can be omitted: link_to("Home", :controller => "home")
 Hi readers,

hope you learn today post.

Leave comment or share.

Friday 3 June 2016

Arithmetic and Conversions, String, Array and Hash

Arithmetic and Conversions:

    2.class == Fixnum 
    Fixnum.superclass == Integer 
    Integer.superclass == Numeric 
     
    3.0.class == Float 
    Float.superclass == Numeric 
     
    2/3 == 0 
    2/3.0 # => 0.6666667 
    2 + 3.0 == 5.0 
    "2".to_i + "3.0".to_f == 5.0 
     
    10000000000.class == Bignum 
    Bignum.superclass == Integer 
     
    2 + "3" # => TypeError: String can't be coerced into Fixnum   

String Class:

    "ruby".upcase + " " + "rails".capitalize # => RUBY Rails 
     
    "time is: #{Time.now}\n second line" 
     
    'no interpolation "here" #{Time.now}' # => no interpolation "here" #{Time.now} 
     
    "I" << "Go" << "Ruby" # => IGoRuby 
     
    %Q{"C" and "Java"} # => "C" and "Java" 
     
    %q{single 'quoted'} # => single 'quoted' 
     
    <<-END 
        A here 
        document at #{Time.now} 
    END  

Array Class:

    a = ["Ruby", 99, 3.14] 
    a[1] == 99 
    a << "Rails" 
    ['C', 'Java', 'Ruby'] == %w{C Java Ruby} 
    [1, 2, 3].map { |x| x**2 }.join(", ") 
    [1, 2, 3].select { |x| x % 2 == 0 } 
    [1, 2, 3].reject { |x| x < 3 } 
    [1, 2, 3].inject { |sum, i| sum + i } 
     
    [1, [2, 3]].flatten! # => [1, 2, 3] 
     
    %w{C Java Ruby}.include?("C") # => true 
     
    fruits = ['apple', 'banana'] 
    fruits += ['apple'] unless fruits.include?('apple') 
    [1, 3, 5] & [1, 2, 3] # (intersection) => [1, 3] 
    [1, 3, 5] | [2, 4, 6] # (union) => [1, 3, 5, 2, 4, 6] 
    [1, 2, 3] - [2, 3] # (difference) => [1]   

Hash Class:

h = {:lang => 'Ruby', :framework => 'Rails'} 
h[:lang] == 'Ruby' 
h[:perl] == nil 
puts h.inspect 
env = {"USER" => "peter", "SHELL" => "/bin/bash"} 
env.each {|k, v| puts "#{k}=#{v}" }

Practice this i will get back to you with new concept.
Subscribe this blog for new updates.

Ruby Object, Constants and Introspection

Everything is an Object:

  • 2 + 2 is equivalent to 2+(2) and 2.send(:+, 2)
  • 2.hours.ago
  • 2.class # => Fixnum
  • 2.class.instance_methods – Object.instance_methods
  • “andreas”.capitalize

Constants:

  • Constants defined in a class/module are available within that class/module and outside the class with the scope operator ::
  • Constants defined outside any class/module can be accessed anywhere
  • Constants cannot be defined in methods

Introspection:

andreas = Person.new("Andreas") 
andreas.inspect # => #<Person:0x1cf34 @name="Andreas"> 
 
andreas.class # => Person 
andreas.class.superclass # => Object 
andreas.class.superclass.superclass # => nil 
 
andreas.class.ancestors.join(", ") # Person, Object, Kernel 
 
Person.instance_methods(false) # => say_hi 
Kernel.methods.sort.join("\n") # => All methods in Kernel module  

Hope you learn something to day.

Follow this blog By subscribing.

Thanks



Thursday 2 June 2016

Ruby Modules and Modules vs Classes

Hi Readers,

Modules:

    require 'person_class' 
    module HasAge 
      attr_accessor :age 
    end 
    class Person 
      include HasAge 
    end 
    peter = Person.new("Peter"); peter.age = 33; puts peter.age 
    module MyApp 
      class Person 
        attr_accessor :hometown 
        def initialize(hometown) 
          self.hometown = hometown 
        end 
      end 
    end 
    peter = MyApp::Person.new("Stockholm"); puts peter.hometown 

Modules vs Classes:

  • Modules model characteristics or properties of entities or things. Modules can’t be instantiated. Module names tend to be adjectives (Comparable, Enumerable etc.). A class can mix in several modules.
  • Classes model entities or things. Class names tend to be nouns. A class can only have one super class (Enumeration, Item etc.).

Hope you understand.

Thanks

 


Wednesday 1 June 2016

Ruby - Assignment concept


Hi Readers,

Today we are going learn assignment of a variable value in ruby.

Assignment:

  • a, b = b, a # swapping values
  • a = 1; b = 1
  • a = b = 1
  • a += 1 # a = a + 1
  • a, b = [1, 2]
  • a = b || c
  • a ||= b

Idiom: Assignment with Boolean Expression

    comment = Object.new 
    def comment.user 
      Object.new 
    end 
     
    # Overly verbose: 
    user_id = nil 
    if comment 
      if comment.user 
        user_id = comment.user.object_id 
      end 
    end 
     
    # Idiomatic: 
    user_id = comment && comment.user && comment.user.object_id  


Practice the above mentioned statements in irb.

Hope you like this.

Thank you

Naming Conventions and Boolean Expressions in Ruby


Hi  Readers,

Remember these things while coding in Ruby. Naming convention is important for good programmer, once you wrote the code it should be in systematic way.

Naming Conventions:

  • MyClass
  • method_name, destructive_method!, question_method?, setter_method=
  • MY_CONSTANT = 3.14
  • local_variable = 3.14
  • @instance_variable
  • @@class_variable
  • $global_variable
Just check your previous code in ruby is written in this naming convention format or not. Practice the naming convention coding to better and clean understanding to others also.

Boolean Expressions:

  • All objects evaluate to true except false and nil
  • false and true are the only instances of FalseClass and TrueClass
  • Boolean expressions return the last evaluated object
  • a and b or c <=> (a and b) or c
  • a = b and c <=> (a = b) and c
  • a = b && c <=> a = (b && c)
  • puts a if a = b # Using assignments in boolean expressions
  • a = true; b = false; a and b and c() # => c() is never invoked
 Good to know the details about the boolean expressions, why because in my experience i face lot of issues with boolean expressions, i found that lot of bugs reported in my past projects most of the bugs having the issue with boolean expressions, So get hands on experience on boolean expression.

Thank for reading.

If you like follow this blog.

Singleton Classes and Methods


Hi Readers,

In this post/page we are going to learn about singleton classes and their methods.

Example:

    require 'person' 
     
    # Every object has two classes: the class of which it is an instance, 
    # and a singleton class. 
    # Methods of the singleton class are called singleton methods 
    # and can only be invoked on that particular object. 
    andreas = Person.new("Andreas") 
    def andreas.andreas_says_hi 
      "Andreas says hi" 
    end 
    andreas.andreas_says_hi 
     
    # Class methods are singleton methods on the class 
    # object and can be defined like this: 
    def Person.count 
      @@count ||= 0 
    end 
    puts Person.count 


In our previous sessions example person class requiring in this, and we are defining a method with the class instance. So here Person in singleton class.

Just go through this example and practice it.

If you like follow the blog.

Thank you.

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...