Skip to content

Instantly share code, notes, and snippets.

@bagwanpankaj
Created October 19, 2010 08:58
Show Gist options
  • Save bagwanpankaj/633877 to your computer and use it in GitHub Desktop.
Save bagwanpankaj/633877 to your computer and use it in GitHub Desktop.
Ruby MetaProgramming Samples
class Testt
define_method :foo do
"welcome"
end
end
Testt.new().foo
=> "welcome"
module Hello
define_method :foo do |name|
"welcome #{name}"
end
end
include Hello
foo "Dave"
=> "welcome Dave"
Testt.instance_eval do
def foo
"I'll be available as class method"
end
def self.bar
"I'll be available as class method"
end
end
Testt.foo
=>"I'll be available as class method"
Testt.bar
=>"I'll be available as class method"
class Testt
end
Testt.class_eval do
def foo
"I'll be available as instance method"
end
def self.foo
"I'll be available as class method"
end
end
Testt.new().foo
=> "I'll be available as instance method"
Testt.foo
=>"I be available as class method"
class User < ActiveRecord::Base
#user has one role so association is
has_one :role
#First time when there is no method found; this method will catch that
def method_missing(method_sym, *params)
#Here we match the pattern of method and see if we can process it or not
if method_sym.to_s =~ /^is_(.*)\?$/
function = $1
self.class.class_eval <<-END
def #{method_sym.to_s}
#{role.name == function.to_s.upcase}
end
END
#Let's register this method with user class when it is invoked first time.
send(method_sym)
else
super
end
end
#Let this class respond for these methods
def self.respond_to?(method_sym, *args, &block)
method_sym.to_s =~ /^is_(.*)\?$/ ? true : super
end
end
class User < ActiveRecord::Base
#user has one role so association is
has_one :role
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment