Ruby symbols

I keep seeing many programmers from different backgrounds are unable to get what Ruby symbols are, and though I do know that there are many great posts regarding this topic, and actually my intent is not to increase them by one :) , but I feel I have to clear few points regarding them.
So I’m trying to answer 2 important question here: What are Ruby symbols? and When to use them?

What are Ruby symbols?

Well, according to the API documentation:

Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :”string” literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

Let’s walk over this long quote, point by point, but let’s first list all the points it has:

1-Symbol objects represent names and some strings inside the Ruby interpreter.
2-They are generated using the :name and :”string” literals syntax, and by the various to_sym methods.
3-The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

I’ll start with the 2nd point then get back to the rest, just before I do, please fire your irb:

We can create a symbol with various ways:

# Normal way, just prefix a token with ':'
greeting = :hi #=> :hi
 
# Multi token symbol 
another_greeting = :"hello man" #=> :"hello man"
 
# Use the .to_sym if it's defined for your object class
# For example .to_sym is defind in String class
a_third_greeing = "howdy".to_sym #=> :howdy
 
# Using %s[ ]
%s[a 4th one] #=> :"a 4th one"
 
# We can also cast a symbol to string with to_s
:ds.to_s #=> "ds"

That was the easy part, now let’s get back to the first point, it says: “Symbol objects represent names and some strings inside the Ruby interpreter.” , what does that mean exactly?

In computer science there is a term called: Symbol table, where the compiler or the interpreter of the language stores all the identifiers of a source code in that table to reference them -specifically to be referenced by the Abstract Syntax Tree(AST).
Actually the data structure that represents the symbol table varies from one interpreter to another, but what we care for is Ruby, in Ruby, the symbol table stores various things like method names and symbol names(we will check why Ruby does so later on), and the value of a symbol is a unique integer value, that can’t be changed.

# Not working on ruby 1.9
:ds.to_i #=> 28777
 
# Notice the value of the symbol is not its object id
:ds.object_id #=> 287778
 
# Symbol values can't be changed
:ds = 3 #SyntaxError: compile error

Now let’s take more in depth example, let’s explore the symbol table:

# Let's check what symbols names start with 'hello'
Symbol.all_symbols.collect{|x| x.to_s}.grep /^hello.*$/ #=> ["hello"]
 
# Now let's define a new dummy class and add  a new method called 'hello_world'
class Dummy; def hello_world; end ; end #=> nil
 
# Check again.
Symbol.all_symbols.collect{|x| x.to_s}.grep /^hello.*$/ #=> ["hello", "hello_world"]

As you can see, when we defined the class ‘Dummy’ and more specifically when we defined the ‘hello_world’ method, it was added to the symbol table.
Let’s take another example:

Symbol.all_symbols.size #=> 3329
:koko #=> :koko
Symbol.all_symbols.size #=> 3330

Now let’s take the last point : “The same Symbol object will be created for a given name or string for the duration of a program’s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.” ,so: Fred is :Fred wherever you see it and no matter what the context it comes in:

k = :Fred  #=> :Fred                  
module M; Cons = :Fred; end #=> :Fred
k.object_id #=> 287498
M::Cons.object_id #=> 287498

When to use Ruby symbols?

Well, this might be the one million dollars question, and that’s initially why i wrote this post for. You also might be wondering, why have Matz chosen to give us this low level introspection in the language by allowing me to work with the interpreter stuff?

The answer is divided in 2 parts:

1- Efficiency. 2- Metaprogramming(reflection).

Efficiency

We will talk about efficiency at first place,so let’s check this snippet of code:

# Some programmer would do this
if name == "khaled alhabache"

The snippet of code above is really costive, in terms of memory and efficiency:
1-Comparing 2 strings is costive, specially when the 2 strings are long.
2-Reserving “changeable” amount of memory, 16 bytes in our case to instantiate “Khaled alhabache”.
3-The GC would have to clean this “Khaled alhabache” later on.

What about doing :

# This is what i call it "a cleaner approach"
if name.to_sym == :"khaled alhabache"

Now what we did is:
1-Comparing 2 integers(the value of a symbol is integer) which is cheaper.
2-Reserving memory 4 bytes for :”Khaled alhabache” symbol, cause a symbol is an integer finally.
3-The GC would not have to clean this :”Khaled alhabache” symbol, cause symbols don’t get deleted till program exits.

So use symbols as much as you can, and avoid using stings as much as you can, but take extra care of defining thousands of symbols, cause as mentioned: symbols don’t get deleted till program exits, and thus they stick in memory.

Metaprogramming and symbols

Well working with metaprogramming in Ruby is really nice, you can do something like:

to = [:to_s , :to_f , :to_r] #=> [:to_s, :to_f, :to_r]
 
# Notice the use of symbols with reflection -Ex with 'send' method 
to.each{|method| puts "#{method} => #{5.send method}"}
# to_s => 5
# to_f => 5.0
# to_r => 5

Without symbols, you would never be able to use reflection techniques like ‘send’, otherwise how can you invoke methods dynamically?, also without symbols, you would never be able to use introspection techniques like ‘respond_to?’

5.respond_to? :slice #=> false
5.respond_to? :to_f #=> true

Update, a respond to readers comments:
It’s true that you can do something like :

5.respond_to? "to_f" #=> true

But what’s happening is that Ruby is casting it for you, but why to reserve extra memory to send it as a string?

For guys who are objecting on memory efficiency with symbols, I strongly recommend reading this post also.

I hope I could help you understand what Ruby symbols are and why they are used for, specially of you who are coming from other programing backgrounds.

Posted in Ruby | Tagged , | 48 Comments

Ruby and Metaprogramming

According to wikipedia, Metaprogramming:

is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at runtime that would otherwise be done at compile time.

Well, nice to hear cause Ruby is a lang that supports Metaprogramming effectively, and might be the best in that field. If you want to explore more on that topic, and how ruby can help you, then check this list of posts i wrote recently, i hope you will enjoy them:

If you have any question regarding this topic, please don’t hesitate to contact me, i would really be pleased to help you.

Posted in Ruby | 5 Comments

Ruby and Internal DSLs

A Domain-specific language(DSL) is a computer language that’s targeted to a particular kind of problem, rather than a general purpose language that’s aimed at any kind of software problem. Domain specific languages have been talked about, and used for almost as long as computing has been done. Regular expressions and CSS are 2 examples of DSLs.

Any software language needs a parser and an interpreter(or compiler or a mix), but in DSLs, we have 2 types: external ones which need parsers and interpreters, and internal ones which rely on the hosting language power to give the feel of a particular language, and thus they don’t require their own parsers.

Ruby is a very convenient language for writing internal DSLs, it has several powerful techniques that enables you easily to write internal DSLs, and many famous products that we use are nothing but internal DSLs: Haml, Builder and Rake .

Lemme show you a very simple example on how an internal DSL might look like using ruby:

RobotTasksExecuter.start do
  stack :boxes => 5 do
    fetch do
      rotate :rectangle => 60
      pick :speed => 'slow',:height => 15
      rotate :rectangle => -60
      free :speed => 'slow'
    end
    package do
      lock
      seal
    end
  end
end

As you can tell, this is a very basic internal DSL, written to describe basic tasks for a robot.
There is one task at the moment called ‘stack’ where the robot should do 2 things: fetch the box, and then package it.
Several ruby techniques are used to bring this basic DSL:
1- Blocks: everything between ‘do .. end’ keywords.
2- Parenthesesless methods: like ‘lock’ and ‘seal’.
3- Passing hash values as method arguments without the need of using curly braces: like doing ‘pick :speed => ‘slow’,:height => 15′.

Now all i need is a simple functionality to execute this simple internal DSL:

# A dummy task class
class RobotTask
  # A dummy run task
  # type of task, a margin to indent the output, and some other attributes are passed
  def run(type,margin,attrs={})
    output = "#{margin} Running task '#{type}'"
    output+=", with attributes:" if !attrs.empty?
    puts output
    attrs.each{|key,value| puts "#{margin} --#{key} = #{value}"}
  end
end
 
# A simple tasks executer 
# This code is very basic and could be far optimized
class RobotTasksExecuter
  def initialize
    puts "   **** Robot is working now ****"
    # This is used to indent the output
    @margin = ""
  end
 
  # Start the executer work
  def self.start(&block)
    # Instantiate an executer object and evaluate the DSL code block
    new.instance_eval(&block)
  end
 
  #  All undefined methods will call method_missing
  #  Let's use 'execute' as an alias for method_missing
  alias method_missing execute
 
  # All undefined methods will call this method, because of the aliasing taking place over.
  def execute(type,attrs={})
    @margin += "  "
    RobotTask.new.run(type,@margin,attrs)
    yield if block_given?
    @margin = @margin[0,@margin.length-2]
  end
 
end
 
RobotTasksExecuter.start do
  stack :boxes => 5 do
    fetch do
      rotate :rectangle => 60
      pick :speed => 'slow',:height => 15
      rotate :rectangle => -60
      free :speed => 'slow'
    end
    package do
      lock
      seal
    end
  end
end

And the output:

   **** Robot is working now ****
   Running task 'stack', with attributes:
   --boxes = 5
     Running task 'fetch'
       Running task 'rotate', with attributes:
       --rectangle = 60
       Running task 'pick', with attributes:
       --speed = slow
       --height = 15
       Running task 'rotate', with attributes:
       --rectangle = -60
       Running task 'free', with attributes:
       --speed = slow
     Running task 'package'
       Running task 'lock'
       Running task 'seal'

In addition to the 3 points we mentioned earlier, another 2 ones should be added, as they are the heart of the above executer:

4- Reflection techniques: the one we used inside the class method ‘start’, exactly this line “new.instance_eval(&block)”.
5- method_missing: all undefined methods are received by ‘execute’, the alias of method_missing.

As i mentioned earlier, this is a very basic internal DSL, if you are looking for an advanced article covering a more advanced one, then don’t hesitate to check this rich one by Daniel Spiewak.

Posted in Ruby | Tagged , , | 8 Comments

Ruby callbacks

This blog post is about ruby’s callbacks(hooks): what are the available ones,and how practically we can use them?

method_missing

obj.method_missing(symbol [, *args] ) => result might be the most famous hook in ruby, and is being used a lot by ruby developers :

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. By default, the interpreter raises an error when this method is called. However, it is possible to override the method to provide more dynamic behavior.

Here is a simple example where the user can mix colors using the mix method :

class Colors 
  def mix(*colors)
    if block_given?
      yield(colors)
    else
      puts "Mixing: #{colors.join ' + '}"
    end
  end
end
c = Colors.new
c.mix "orange" , "cyan" #=> Mixing: orange + cyan
c.mix("green","red"){|colors| puts "A nice mix: #{colors.join(' + ')}"} #=> A nice mix: green + red

Now, how about letting the user do something like: ‘c.greenAndBlue’ or ‘c.grayAndYellow’ ?, let’s see how to do so:

class Colors 
  def mix(*colors)
    if block_given?
      yield(colors)
    else
      puts "Mixing: #{colors.join ' + '}"
    end
  end
 
  def method_missing(*args, &block)
    # First arg is a symbol representing the name of the method.
    method_name = args.shift
    # Extract the colors from the method name and collecting them in an array 
    # This is a very basic treatment.
    colors = method_name.id2name.split(/and/i).collect{|color| color.downcase}
    # Send the colors and the block to 'mix' method.
    self.send :mix, colors ,&block
  end
end
 
c = Colors.new
c.mix "orange" , "cyan" #=> Mixing: orange + cyan
c.mix("green","red"){|colors| puts "A nice mix: #{colors.join(' + ')}"} #=> A nice mix: green + red
c.greenAndBlue #=> Mixing: green + blue 
c.greenAndWhiteAndBrown #=> Mixing: green + white + brown
c.grayAndYellow{|colors| puts "A nice mix: #{colors.join(' + ')}"} #=> A nice mix: gray + yellow

const_missing

const_missing : invoked when a reference is made to an undefined constant.

I will use it to show the user a more informative message when he tries to use a non existing constant:

class Colors
	RED = "#FF0000"
	GREEN = "#00FF00"
	BLUE = "#0000FF"
 
	def self.const_missing(name)
		puts "Sorry the color '#{name}' is undefined; #{constants.join ","} are the only available colors."
	end
end
 
Colors::Yellow #=> Sorry the color 'Yellow' is undefined; BLUE,GREEN,RED are the only available colors.

included and extended

included and extended are fired when the module is included or extended :

module A
	def self.included(base)
		puts "#{self} included in #{base}"
	end
 
	def self.extended(base)
		puts "#{self} extended in #{base}"
	end
end
 
class B
	include A #=> A included in B
end
 
class C
	extend A #=> A extended in C
end

However let’s move to a more practical use, if u look at the module documentation, you will find the following definition:

A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not.

Well, as you can see, you can’t include the module methods inside your class, then what to do?
I saw some people use a nice trick to do so, they split their module into 2 inner modules, one called InstanceMethods and the other called SingletonMethods, then they include the former, and extend the later, look at the following snippet of code :

module Greetings
  # When a class is including this module
  def self.included(base)
    # include: will mix the methods in the caller as instance ones.
    # include: is a private method that's why we are using 'send'
    base.send :include, InstanceMethods
    # extend: will mix the methods in the caller as class ones.
    # extend: is a private method that's why we are using 'send'
    base.send :extend, SingletonMethods
  end
 
  # Put all the the methods that should be mixed as instance ones here.
  module InstanceMethods
    def hello ; puts "hello" ; end
  end
 
  # Put all the the methods that should be mixed as class ones here.
  module SingletonMethods
    def bye ; puts "bye!" ; end
  end
end
 
class Greeter
  # The 'included' callback is getting fired now 
  include Greetings
end
 
Greeter.new.hello #=>hello
Greeter.bye #=> bye!

method_added and singleton_method_added

method_added and singleton_method_added are another 2 callbacks that are fired when a new instance or singleton method is added.
In the code snippet bellow, I’m trying to prevent a developer from monkey patching(reopen) my colors class:

class Colors
  def self.method_added(name)    
    puts "A trial to add a new instance method: #{name}, this is not allowed." 
    undef_method name
  end 
 
  def self.singleton_method_added(name)   
    if name != :singleton_method_added
      singleton_class = class << self; self; end
      puts "A trial to add a new class method: #{name}, this is not allowed." 
      singleton_class.class_eval{undef_method name}
    end
  end 
end
 
#Monkey patching 
class Colors
  def red ; end #A trial to add a new instance method: red, this is not allowed.
  def self.mixer ; end #A trial to add a new class method: mixer, this is not allowed.
end

method_removed and method_undefined

method_removed: fired when an instance method is removed.
method_undefined: fired when an instance method is undefined.

singleton_method_removed and singleton_method_undefined

singleton_method_removed: fired when a singleton method is removed.
singleton_method_undefined: fired when a singleton method is undefined.

inherited

inherited is called when some class is being inherited:

class Colors
  def self.inherited(sub)
    puts "class #{sub} is inheriting class #{self}"
  end
end
 
class C < Colors ; end #=> class C is inheriting class Colors

A practical use will be in preventing subclasses from being created :

class Colors
  def self.inherited(sub) 
    raise "class #{sub} is inheriting class #{self}, inheritance is now allowed...."
  end
end
 
class D < Colors ; end #=> class D is inheriting class Colors, inheritance is now allowed.... (RuntimeError)

Well, that’s all for this post. The next post series will be on writing internal DSLs using ruby.
See you then…..

Posted in Ruby | 9 Comments

Ruby reflection 2

This is the second post related to ruby’s reflection API, the previous post was an extensive intro to this topic. While the current one will be lighter somehow, it would require you to focus a bit more on the content.
Here we go:

Setting, getting and removing instance variables :

# Define a simple class M
class M ; end #=> nil
 
m = M.new #=> #<M:0xb764b7e0>
 
# Set an attribute i with value 5, the attribute name should be a symbol prefixed with @
m.instance_variable_set :@i , 5 #=> 5 
 
# This will never work cause no attribute reader is defined for 'i'
m.i #=>NoMethodError: undefined method `i' for #<M:0xb764b7e0 @i=5> from (irb):4
 
# Get it the right way!
m.instance_variable_get :@i #=> 5

The code above could be written in a simpler way, let’s define another attribute ‘v’ for example :

# Use class_eval , and pass it a block of code :
M.class_eval { attr_accessor :v} #=> nil
 
# Set and get the attribute v
m.v = 8 #=> 8
m.v #=> 8

Now, let’s undefine the instance variable ‘i’

m.remove_instance_variable :@i  #=>NoMethodError: private method `remove_instance_variable' called for #<M:0xb767d4c0 @v=8  from (irb):29
 
# Opps, a private method! let's bypass that with instance_eval
m.instance_eval{remove_instance_variable :@i} #=> 5      ,
 
# Could be accomplished with :send
m.send :remove_instance_variable , :@i #=>5
m.i #=> nil

Setting, getting and removing class variables :

As instance_variable_get and instance_variable_set, there are another variations applied to class variables, but unfortunately they are private in ruby 1.8, so let’s use class_eval to bypass that:

M.class_eval {class_variable_set :@@ci ,1} #=> 1
M.class_eval {class_variable_get :@@ci} #=> 1
M.class_eval {remove_class_variable :@@ci } #=> 1

Setting, getting and removing constants :

How about constants?

M.const_set :CON , "I'm a constant" #=> "I'm a constant"
M.const_get :CON #=> "I'm a constant"
M.const_defined? :CON #=> true
 
 
# Let's remove it with "send" method
M.send :remove_const , :CON #=> "I'm a constant"
M.const_defined? :CON #=> false

define_method

Now let’s move to a new topic:
Define a method dynamically using define_method:
As the API tells :

Defines an instance method in the receiver. The method parameter can be a Proc or Method object. If a block is specified, it is used as the method body. This block is evaluated using instance_eval, a point that is tricky to demonstrate because define_method is private.

# define_method is a private method, that's why we use the 'class_eval' method
String.class_eval {define_method(:len){length}} #=> #<Proc:0xb7635e68@(irb):17>
"how much long am I?".len #=> 19
 
# You can use the 'send' method instead of 'class_eval', notice how we are sending a Proc object to define_method
String.send :define_method,:len2,lambda {length}
"how much long am I?".len2 #=> 19

When using a block, the block params will be the method params:

String.class_eval{define_method(:part){|s,e| self[s,e] } } #=> #<Proc:0xb7699364@(irb):14>
"hello world!".part(1,4) #=> "ello"

Let’s use it to redefine the ‘attr_access’ in another way rather than the way that was defined in the previous post

class Class
  def attr_access(*attrs)
    attrs.each do |attr|
      define_method :"#{attr}=" do |value|
        instance_variable_set("@#{attr}",value) 
      end
 
      define_method :"#{attr}" do
        instance_variable_get "@#{attr}"
      end
    end
  end
end

One limitation to ‘define_method’ is that: it always creates instance methods, thus if we want to use it to define class methods, then we need to invoke it on the singleton class, let’s define the ‘cattr_access’ method:

class Class
   def cattr_access(*attrs)
    singleton_class = class << self; self; end
    attrs.each do |attr|
      singleton_class.class_eval do 
        define_method :"#{attr}=" do |value|
          class_variable_set("@@#{attr}",value)
        end
        define_method :"#{attr}" do
          class_variable_get "@@#{attr}"
        end
      end
    end
  end
end

Notice how i defined the singleton_class as a local variable, it could be defined using a method, just like what we did in the previous post, however, notice: how complex it became to use the define_method to define a class method, i wouldn’t encourage at all such a complexity.

Undefining methods

How about undefining methods? That can be accomplished in 2 ways: either by using the ‘undef’ statement, or using the private ‘undef_method’ method:

String.class_eval{undef :len} #=> nil
String.send :undef_method ,:len2 #=> String

Alias chaining

One last thing that deserves mentioning here: is the ‘alias_method’, it’s being used to have alias chaining:
1- Copy the original method and give it an alias to be used later.
2- Create a new method with the same name of the original one, do whatever changes you need, and use the alias to invoke the original method somewhere inside the new one.
Before i show you the example i have to mention the ruby statement ‘alias’ which can be used as ‘alias_method’ :

# I want to modify the 'puts' method to make it more expressive, at least for me!
#' puts' is defined in Kernel module.
# Copy the method "puts", and assign it a new name: "original_puts"
alias :original_puts :puts #=> same as doing:   Kernel.send :alias_method ,:original_puts ,:puts
 
# Now define the method again, and use the original method functionality to help expressing the new functionality. 
def puts(*args)
   args.each_with_index do |arg,index|
	original_puts "value of parameter #{index+1} =>  #{arg}"
   end
end
 
puts 1,2,3
#value of parameter 1 =>  1
#value of parameter 2 =>  2
#value of parameter 3 =>  3

I hope you liked this post, please don’t hesitate to notify me about hidden mistakes or suggest new stuff.
I’ll blog on using ruby’s hooks(callbacks) in the next blog post, stay in touch…..

Posted in Ruby | Tagged , , | 3 Comments

Ruby reflection

If you are here, then most probably you want to know more about ruby reflection interface. Well that’s true, but I always find myself in need to explain few things before I get started with my posts, and this time I find myself in need of explaining few things related to ruby’s OOP.

I’m pretty sure that you always heard that “in ruby: everything is an object.” , but have you ever thought of that carefully?
The first thing that comes to a one’s mind is something like :

5.class #=> Fixnum
"hello".class #=> String

But have you thought of your class as an object? Well that seems odd, but that’s how ruby works:

class Foo;end  #=> nil
Foo.class #=> Class

What does the above snippet of code mean exactly?
It means 2 things : Foo is a constant and that constant holds(refers to) an object of Class type.

Let me prove that 2 you:

Foo = Class.new
(irb):8 warning: already initialized constant Foo
=> Foo

As you can see, I got a warning because I tried to initialize the constant Foo again.

So ,when you define some class ‘Foo’ in ruby, all you are doing is:
1-instantiating an object of type Class.
2-initializing a constant Foo that refers to that created object .

So bear in mind that when I say “object” ,then I do mean any object; an object of Class type, or any object of any type.

Now, let’s move to another point. What about the ‘Singleton Class’, did you have the chance to work with it before?
Simply it’s the class that holds all singleton methods of an object, whether it’s a class object , or any other object.

Let’s start by defining 2 class methods (a class method is nothing but: a singleton method of an object of Class type) :

class Foo
  def self.hi ; p "hi" ;end
  def self.bye ; p "bye" ; end
end
Foo.singleton_methods #=> ["hi","bye"]

You could also have written that in this way:

class Foo
  class << self
    def hi ; p "hi" ; end
    def bye ; p "bye" ; end
  end
end
Foo.singleton_methods #=> ["hi","bye"]

The above inner class mentioned with “class << self" is what we call : a singleton class.
Let's define a method that returns back the singleton class for us :

class Object
  def singleton_class 
     class << self
       self
     end
  end
end

Now try this :

Foo.singleton_methods #=> ["bye", "hi"]
Foo.singleton_class.instance_methods(false) #=> ["bye", "hi"]

As you can see, the singleton class is the class that holds all singleton methods.
We will use the singleton class later in this series, so keep the concept in mind.

Let’s now get back to our topic on ruby’s reflection api , i will introduce 3 methods in this post: eval , instance_eval and class_eval.

eval

‘eval’ is a method that evaluates a ruby string :

eval "3+4" #=> 7
eval "def multiply(x,y) ; x*y; end"
multiply(4,7) #=> 28

eval can also work in the scope of bindings ; a binding is an object that encapsulates the execution context at some particular place in the code and retain this context for future use. Look at this example of using bindings with eval :

class Demo
  def initialize(n)
    @secret = n
  end
  def getBinding
    return binding()# a method defined in Kernel module
  end
end
k1 = Demo.new(99)
#get the value of the instance variable @secrete stored in the binding of object k1
eval("@secret", k1.getBinding)   #=> 99

Also can work with proc objects :

def greeting(name)
  lambda{|greetings| greetings.collect {|g| "#{g} #{name}"} }
end
greeter = greeting("dude") #=> #<Proc:0xb752b810@(irb):2>
greeter.call ["hi","hello","hola"] #=> ["hi dude", "hello dude", "hola dude"]
eval("name='khelll'",greeter) #=> "khelll"
greeter.call ["hi","hello","hola"] #=> ["hi khelll", "hello khelll", "hola khelll"]

instance_eval

This method works in the context of the object :

class Klass
  def initialize
    @secret = 99
   end
end
k = Klass.new
k.instance_eval { @secret }   #=> 99 , notice the @

And could be used to define singleton methods :

Fixnum.instance_eval "def zero; 0 ;end"                                                 
Fixnum.zero #=> 0

you can pass it a block instead of the string :

Fixnum.instance_eval{ def ten ;10;end }
Fixnum.ten #=> 10

class_eval

Evaluates a string or a block in the context of the receiver

Foo.class_eval{@@x=1} #=> 1
Foo.class_eval{@@x} #=> 1

And it defines instance methods when called on some object

Fixnum.class_eval "def number ; self ;end"
5.number #=> 5

And as instance_eval, a block instead of the string could be passed

Fixnum.class_eval{ def number;self;end}
7.number #=> 7

You can use class_eval to dynamically use private methods, for example to use the private method ‘include’:

module M; end
String.include M #=> NoMethodError: private method `include' called for String:Class
String.class_eval{include M} #=> you could do it with String.send(:include,M)

Now let’s make use of our knowledge,let’s try to redefine the attr_accessor method in our way, I will make a similar method called attr_access :

class Class
  def attr_access(*attrs)
    attrs.each do |attr|
      class_eval %Q{
	    def #{attr} 
	      @#{attr}
	    end
	    def #{attr}=(value)
	      @#{attr} = value
	    end
      }
    end
  end
end
 
class Foo 
 attr_access :a,:b 
end
 
Foo.instance_methods(false) #=> ["b=", "a=", "b", "a"]

in a similar way we can define class attribute accessors :

class Class
    def cattr_access(*attrs)
      attrs.each do |attr|
        class_eval %Q{
  	    def self.#{attr}
  	      @@#{attr}
  	    end
  	    def self.#{attr}=(value)
  	      @@#{attr} = value
  	    end
        }
      end
    end
end

Or with we can use the singleton class :

class Class
  def singleton_class 
    class << self
      self 
    end 
  end
 
  def cattr_access(*attrs)
    attrs.each do |attr|
      singleton_class.class_eval %Q{
        def #{attr}
  	   @@#{attr}
  	 end
  	 def #{attr}=(value)
  	    @@#{attr} = value
  	 end
       }
    end
  end
end

And in both cases we can do :

class Foo ; cattr_access :cx,:cy end
Foo.singleton_methods(false) #=> ["cy", "cy=", "cx", "cx="]

Give it a try and try to define attr_reader and attr_writer for both object and class variables.

I think it’s enough for this post, the next post will contain more methods to look at. See you then.

Update 1: fixing some typos.
Update 2: second part is here.

Posted in Ruby | Tagged , | 16 Comments

Arabs who are interested in Merb and Merb-book

So many developers from various countries had corresponded to Matt Aimonetti’s article on open merb book, and an early version of the book is out there.

However lot’s of work is still needed in both directions: contribution and translation ,so: dear Arabic developers wherever you are, if you are interested in Merb framework, have the ability to write in native Arabic, and willing to help contributing or translating the merb-book , then please don’t hesitate to send me an email. Your efforts is gonna be highly appreciated by Merb community, and you personally gonna gain lot’s of knowledge in Merb framework, how to contribute to open source, and how to write a book.

Waiting to here from you…..

Posted in Merb | Tagged , | 2 Comments

What i liked most about rails 2.2

Well, finally it’s there, many important improvements were added to rails 2.2, and yet new things are on the way, you can check this blog post to check what’s new, while i’m gonna list here what i really liked about the new version of rails 2.2:

Thread safe

If you really don’t know what it means, then most probably you want to check this post by Charles Nutter, however in short terms: threaded rails with a native threaded implementation of ruby (jruby in our case) will save your memory , make your app more scalable, and most importantly it will make the app deployment very easy, specially when glassfish gem or even with jetty-rails gem is used.

And you Just have to make sure your app is thread safe, follow this post by Pratik Naik.

Well documented

So many people complained about this point before, but this a fact is from past now :) , just fire your terminal , go to ur app path, and run :

rake doc:guides

This will create doc/guides in your project root , with a comprehensive rails guide to learn from.

Internationalization or I18n

A support for i18n is there now, so  you don’t have to install any extra gem or plugin, a comprehensive demo is put there, just be aware that you don’t need to install the plugin when following the demo, cause it’s already there in rails 2.2 .

Also check the I18n screencast by Ryan Bates.

Performance + JRuby compatibility

  • Connection pooling is added in this version of rails , which will save the time of opening(open connection with the db server +authentication) and closing the connection for each http request, so now a pool of connections will be used to serve incomming http requests, instead of opening a new connection for each request.
  • There were efforts to enhance the erb system , which will affect the rendering process time.
  • Rails 2.2 is fully compatible with JRuby which is the fastest ruby implementation at the current moment, and that will give you better performance when JRuby is used ,specially that the JRuby team is continually and actively(a release every 3-4 weeks) working on optimizing the overall performance and for rails usage as well.
  • Memoization term was introduced to cache values, check this screencast by Ryan Bates.
  • ETags and saving your server the hassle : if u don’t know about ETags then it’s time for that , check this post by  Ryan Daigle.What matters here is that the new support from rails to ETags  will give you 2 enhancements :
    1. Frontend enhancement: the client browser will use it’s cache to render the needed data and thus won’t need to issue a new request to your server to bring the data, thus a faster rendering on client side.
    2. Backend enhancement: your ror servers won’t need to handle some logic to respond back to your client browser requests, thus free the processor to handle other logic.
  • Template views will be cached now for production mode.

Caching actions without their layouts

Now it’s possible to cache an action without it’s corresponding layout:

class HomepageController < ApplicationController
  # Just pass the param layout with false value
  caches_action :feedback, :layout => false
  ...
end

This is really cool, cause in many cases our layout will contain some info related to user status in the website.

More additions might be very interseting for you

As for me, those enhancements and additions listed above , where the most benifitical for my work, other things might attract your attention, for more information about what’s new, i strongly urge you to look at Ruby on Rails 2.2 PDF by By Carlos Brando.

Posted in Merb + RoR3 | Tagged , , | 1 Comment

Ruby introspection 2

I wanted to start blogging on ruby reflection api, but i just realized that i have to give a second part of my previous article on ruby introspection .
So here we go:

s = ''
#  s.is_a? String, this is the same!
String === s
 
# Determines whether the object has a public or protected method with the specified name.
s.respond_to? :slice #=>true
 
# Or
String.respond_to? :include #=> false
 
# Passes true as the second argument to check private methods as well.
String.respond_to? :include , true #=> true
 
# Check whether some module includes another
module M1 ; end
module M2 ; include M1 ; end
M2.include? M1 #=> true
 
# Check whether instance variable is defined or not.
d=Date.new
d.instance_variables #=> ["@sg", "@of", "@ajd"]
d.instance_variable_defined? "@of" #=>true
 
# I have to clarify this, a note for the previous post:
# obj.public_methods(all=true) ,returns the list of public methods accessible to obj. If the all parameter is set to false, inherited methods will be excluded.  
# obj.protected_methods(all=true),returns the list of protected methods accessible to obj. If the all parameter is set to false, inherited methods will be excluded.  
# obj.private_methods(all=true),returns the list of private methods accessible to obj. If the all parameter is set to false, inherited methods will be excluded.
# Ex:
d.public_methods #=> [">>", "between?", "h!", "methods", "send", "ctime", "history_write", "year", "h", "taint", "to_enum", "instance_variable_defined?", "history", "ld", "_dump","q", "singleton_methods", "instance_eval", "os?", "wday", "enum_for", "nil?", "succ", "pretty_print_cycle", "asctime", "po", "protected_methods", "instance_exec", "start", "tainted?", "ns?", "handling_jruby_bug", "new_start", "yday", "untaint", "instance_of?", "equal?", "taguri", "pretty_print", "julian?", "step", "amjd","hash", "poc", "private_methods", "jd", "newsg", "taguri=", "history_to_vi", "pretty_print_instance_variables", "ajd", "italy", "kind_of?", "freeze", "eql?", "next", "to_yaml_style", "id", "sg", "public_methods", "hvi", "quiet", "england", "is_a?", "mday", "tap", "type", "ri", "to_yaml_properties", "+", "instance_variables", "__id__", "frozen?", "-", "julian", "pretty_inspect", "to_a", "cwyear", "respond_to?", "upto", "display", "history_do", "day", "method", "class", "verbose", "gregorian?", "downto", "mjd", "strftime", "<=>", "instance_variable_get", "==", "__send__", "leap?", "===", "gregorian", "pretty_print_inspect", "extend", "to_s","cweek", ">=", "v", "mon", "<=", "clone", "to_yaml", "=~", "instance_variable_set", "<", ">", "cwday", "inspect", "day_fraction", "month", "dup", "object_id", "<<"]
 
d.public_methods(false) #=> ["jd", "month", "_dump", "ctime", "ld", "cweek", "succ", "to_s", "step", "day", "gregorian?", "hash", "ajd", "julian", "+", "yday", "taguri", "os?", "strftime", "italy", "downto", "-", "eql?", "sg", "year", "asctime", "leap?", "taguri=", "inspect", "amjd", "cwday", "to_yaml", "mon", "<<", "gregorian", "newsg", ">>", "start", "cwyear", "day_fraction", "mday", "ns?", "mjd", "england", "upto", "wday", "<=>", "julian?", "new_start", "===", "next"]
 
#Check if a method is defined
String.method_defined? :slice! # => true 
 
# Check if public method is defined?
String.public_method_defined? :upcase     # => true
 
# Check if protected method is defined?
String.protected_method_defined? :downcase  # => false 
 
# Check if private method is defined?
String.private_method_defined? :initialize # => true 
 
# Check local variables
local_variables
 
# Check class variables
class One ; @@var1 = 1 ; end
class Two < One ; @@var2 = 2 ; end
One.class_variables   #=> ["@@var1"]
Two.class_variables   #=> ["@@var2", "@@var1"]
 
# Check constants
Math.constants #=> ["PI", "E"]
 
# Check global variables
global_variables #=> ["$fileutils_rb_have_lchmod", "$binding", "$-w", "$:", "$.", "$KCODE", "$-F", "$*", "$stderr", "$,", "$`", "$-p", "$\"", "$$", "$<", "$@", "$-v", "$-i", "$deferr", "$\\", "$=", "$;", "$PROGRAM_NAME", "$stdout", "$&", "$fileutils_rb_have_lchown", "$-d", "$LOAD_PATH", "$-a", "$VERBOSE", "$FILENAME", "$defout", "$-0", "$+", "$0", "$stdin", "$~", "$DEBUG", "$-I", "$_", "$-K", "$>", "$/", "$'", "$-l", "$LOADED_FEATURES", "$?", "$SAFE", "$!"]
 
# How to get the name of the current method?
# Add this snippet of code to your logic somewhere
 
module Kernel
  private
  # Defined in ruby 1.9
  unless defined?(__method__)
    def __method__
      caller[0] =~ /`([^']*)'/ and $1
    end
  end
end

Also i strongly recommend that you look at the ObjectSpace module which contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator, however this is a little example taken from the official api documentation :

#ObjectSpace.each_object([module]) {|obj| ... } => fixnum
#Calls the block once for each living, nonimmediate object in this Ruby process. If module is specified, calls the block for only those classes or modules that match (or are a subclass of) module. Returns the number of objects found. Immediate objects (Fixnums, Symbols true, false, and nil) are never returned. In the example below, each_object returns both the numbers we defined and several constants defined in the Math module.
 
a = 102.7
b = 95       # Won't be returned
c = 12345678987654321
count = ObjectSpace.each_object(Numeric) {|x| p x }
puts "Total count: #{count}"
 
#=>12345678987654321
#102.7
#2.71828182845905
#3.14159265358979
#2.22044604925031e-16
#1.7976931348623157e+308
#2.2250738585072e-308
#Total count: 7

Also if you feel like you are eager to see low level introspection , then check this great post.

In my next article, am going to blog on ruby reflection api , hope to finish it soon ;)

Posted in metaprogramming, Ruby | Tagged , , | Leave a comment

Changing database encoding from latin1 to UTF8

Now a days, UTF-8 is the most used data encoding format, and the fact that your database is not using UTF8 encoding is really annoying, specially additionally when it comes to integrating different systems, that has no one unified encoding format.
So if you think it’s time to change your data encoding to utf8 format, then here what this post is all about.
I’ll list here the steps to do so, i just have to clarify that the main data encoding here is windows-1256 (which is the main Arabic encoding used in web applications), but it’s saved in latin1 encoding in the database (mydata ->windows-1256 -> latin1) ,also note that i’m using Mysql database.
Here are the steps:

  1. Export (only) the schema of the db,without “set Names” phrase in the outputted sql file, this will bring you back the data in the original encoding (windows-1256)
    mysqldump --default-character-set=latin1 --skip-set-charset -d -uusername -ppassword db_name > db_name_schema.sql
  2. Export the data of the db without “set Names” phrase in the outputted sql file, this will bring you back the data in the original encoding (windows-1256):
    mysqldump --default-character-set=latin1 --skip-set-charset -t -uusername -ppassword  db_name > db_name_data.sql
  3. Change the encoding of both files from arabic to utf8 -check the notes if you r using windows
    iconv -f windows-1256 -t utf8 db_name_schema.sql > db_name_schema_utf8.sql
    iconv -f windows-1256 -t utf8 db_name_data.sql > db_name_data_utf8.sql
  4. Open the file ‘db_name_schema.sql’ with any editor and replace each “DEFAULT CHARSET=latin1″ phrase with “DEFAULT CHARSET=utf8″ one
  5. Make a new db ,encoded in utf8:
     mysql -uusername -ppassword -e 'CREATE DATABASE new_db DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci'
  6. Import the schema and data in utf8 encoding:
    mysql --default-character-set=utf8 -uusername -ppassword new_db < db_name_schema_utf8.sql
    mysql --default-character-set=utf8  -uusername -ppassword new_db < db_name_data_utf8.sql

notes

  • If you are wondering why to separate schema from data upon exporting , then the answer is that the operation of replacing “DEFAULT CHARSET=latin1″ phrase with “DEFAULT CHARSET=utf8″ one , is taking place only on schema files, so it’s recommended to separate them so that you dont stuck when loading the big data files.
  • If you are a windows user and can’t use iconv , then u can use any editor to do the job for u, try scite or note++ or even dreamweaver

enjoy!!!

Posted in mysql | Tagged , , | 14 Comments