May 25 2011

Don't Forget Ruby's Send Method

Ruby Rails | comments

First of all thank you for reading. Thanks to those who thanked me for blogging. Been very busy and hardly found time to blog.

In the past few years, Ruby's send method saved me from having to write several lines of code. Don't you ever forget about it.

Let me show you a simple example which is actually very fun because it has to do with social networks or third party services.

Goal: we want to display the logo of Twitter, Facebook and Google along with the links if the user is not authenticated (has not successfully authorized the application to access and write data to the third party service) or if the user is not a current user.

This is how we write that if we use devise and omniauth:

                - resource_class.omniauth_providers.each do |provider| 
                  =link_to "Connect via #{provider.to_s.titleize}" ,  omniauth_authorize_path(resource_name, provider), :class=>"#{provider.to_s}_login_icon clearFix" unless (current_user and current_user.send(provider.to_s))
              

So by now you've figured out that I have some instance methods on a module that would either return true, false or nil.

              on user.rb
              
              include User::Authentications 
              
              on user/authentications.rb
              
              module User::Authentications 
                  
                def self.included(base)
                  base.send(:include, InstanceMethods)
                end
                
              
                module InstanceMethods
              
                  def facebook
              
                    begin
                      @fb_user ||= FbGraph::User.me(self.authentications.find_by_provider('facebook').token)
                    rescue
                      return nil
                    end
                  end
              
                 def twitter
                   #some code here
                 end
              
                 def google_apps
                   #some code here 
                 end 
                end
              
              
              end
              
              

Took out the code for twitter and google apps. But you should realize the benefit of the send method if you were developing something more complex and had more instance methods. Prior to this, I remember using send method for a psychology quiz application.

More on Ruby's send method:

              
              on_class = "Post"
              on_class.constantize.send("method_name")
              on_class.constantize.send("method_name", arg1)
              
              

We can use constantize to convert string to a constant as the name suggests.