Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-17 of 17 total

get the name of the calling methos

caller_method_name() gets you the name of the calling method.
you could also get the line and file in which the method is called.

   1  
   2  
   3  def caller_method_name
   4      parse_caller(caller(2).first).last
   5  end
   6  
   7  def parse_caller(at)
   8      if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at
   9          file = Regexp.last_match[1]
  10  		line = Regexp.last_match[2].to_i
  11  		method = Regexp.last_match[3]
  12  		[file, line, method]
  13  	end
  14  end
  15  

Get the currently running method name in Ruby

from: http://www.ruby-forum.com/topic/75258

Author: Robert Klemme


   1  
   2  
   3  module Kernel
   4   private
   5      def this_method_name
   6        caller[0] =~ /`([^']*)'/ and $1
   7      end
   8  end
   9  
  10  
  11  class Foo
  12   def test_method
  13     this_method_name
  14   end
  15  end
  16  
  17  puts Foo.new.test_method    # => test_method
  18  

Adding virtual methods to Ruby

From:
http://ozone.wordpress.com/2006/02/28/adding-virtual-methods-to-ruby/

Author: Olivier Ansaldi


   1  
   2  
   3  class VirtualMethodCalledError < RuntimeError
   4    attr :name
   5    def initialize(name)
   6      super("Virtual function '#{name}' called")
   7      @name = name
   8    end
   9  end
  10  
  11  class Module
  12    def virtual(*methods)
  13      methods.each do |m|
  14        define_method(m) {
  15          raise VirtualMethodCalledError, m
  16        }
  17      end
  18    end
  19  end
  20  
  21  
  22  # The usage is beautifully simple:
  23  
  24  class VirtualThingy
  25    virtual :doThingy
  26  end
  27  
  28  class ConcreteThingy < VirtualThingy
  29    def doThingy
  30      puts "Doin' my thing!"
  31    end
  32  end
  33  
  34  begin
  35    VirtualThingy.new.doThingy
  36  rescue VirtualMethodCalledError => e
  37    raise unless e.name == :doThingy
  38  end
  39  ConcreteThingy.new.doThingy
  40  
  41  

helper to determine if radio/checkbox needs to be checked

I frequently have to use methods such as 'radio_button' and 'check_box_tag' when I don't have an object with a method that will automatically determine the value of the input field. Therefore, I have to check to see if a certain parameter has been passed, and if so, if the parameter's value matches that of the input's value. This method does that.

It's designed to be used in a Rails helper. You can either pass it the object, method, and value (the same parameters as, for example, radio_button) or name and value (the same parameters as radio_button_tag).

   1  def checked?( *args )
   2    if args.length == 3
   3      object, method, value = args
   4      if params[object] && params[object][method] && params[object][method] == value
   5        'checked'
   6      end
   7    elsif args.length == 2
   8      name, value = args
   9      if params[name] && params[name] == value
  10        true
  11      end
  12    end
  13  end


Here's an example usage:
   1  <%= radio_button 'person', 'age', '12', :checked => checked?( 'person', 'age', '12' ) %>


If params[:person][:age] exists and it equals '12', then 'checked?' returns 'checked'; otherwise, it returns nil.

Easy default options for methods in Ruby

   1  
   2  def my_method(opts={})
   3    {:arg_one => 'foo', :arg_two => 'two'}.merge(opts)
   4  end

Temporarily overriding class methods in Ruby

By Tobi / xal from IRC, and seemingly related to this.

   1  class Object
   2    def mock_methods(mock_methods)
   3   
   4      original = self
   5   
   6      klass = Class.new(self) do
   7   
   8        instance_eval do       
   9          mock_methods.each do |method, proc| 
  10            define_method("mocked_#{method}", &proc)
  11            alias_method method, "mocked_#{method}"
  12          end            
  13        end
  14   
  15      end
  16   
  17      begin
  18        Object.send(:remove_const, self.name.to_s)
  19        Object.const_set(self.name.intern, klass)
  20   
  21        yield
  22   
  23      ensure
  24        Object.send(:remove_const, self.name.to_s)
  25        Object.const_set(self.name.intern, original)
  26      end
  27   
  28    end
  29  end
  30   
  31  class Duck
  32    def quak; puts "Quak";  end
  33  end
  34   
  35  Duck.new.quak #=> "Quak"
  36   
  37  Duck.mock_methods(:quak => Proc.new { puts 'Wuff' }) do  
  38    Duck.new.quak #=> "Wuff"
  39  end

classmethod and staticmethod

   1  
   2  class K(object):
   3  
   4    # normal method (instance method)
   5    def method1(self):
   6      print 'obj.method1() becomes method1(obj)'
   7  
   8    # class method
   9    def method2(cls):
  10      print 'K.method2() becomes method2(K)'
  11    method2 = classmethod(method2)
  12  
  13    # static method
  14    def method3():
  15      print 'K.method3() become just method3()'
  16    method3 = staticmethod(method3)
  17  
  18  obj = K()
  19  obj.method1()
  20  K.method2()
  21  K.method3()
« Newer Snippets
Older Snippets »
Showing 11-17 of 17 total