Datt Dongare
I've expertise in web development using Ruby on Rails and ReactJS. I help teams to write better code and also mentor them for organizing the projects efficiently
class MethodCaller
def initialize(foo)
@foo = foo
end
def perform(action)
@foo.send action
end
end
method_caller = MethodCaller.new(9)
method_caller.perform("to_f")
class Friend
def initialize(friend)
@friend = friend
end
private
def all
friends
end
end
new_friend = Friend.new
new_friend.send(:all)
class Notification
%w{ create update delete }.each do |action|
define_method("emit_#{action}".gsub(/e$/, 'ing')) do |something|
"#{action} is performed on #{something.class}"
end
end
end
notification = Notification.new
puts notification.emit_creating user
# create is performed on User
puts notification.emit_deleting account
class Timeline
attr_reader :tweets
alias_method :contents, :tweets
def initialize(tweets = [])
@tweets = tweets
end
end
Module#undef_method
- removes method, including the inherited ones.
Module#remove_method( )
- removes the method from the receiver, but it leaves inherited methods alone.
Example 1 using undef_method
class A
def x
puts "x from A class"
end
end
class B < A
def x
puts "x from B Class"
end
undef_method :x
end
obj = B.new
obj.x
result: undefined methodx' for # (NoMethodError)
class A
def x
puts "x from A class"
end
end
class B < A
def x
puts "x from B Class"
end
remove_method :x
end
obj = B.new
obj.x
x from A class
klass = Object.const_get('String')
obj = klass.new
obj.length
class String
def write_size
self.size
end
end
size_writer = "Tell me my size!"
puts size_writer.write_size
class Person
end
Person.class_eval do
def say_hello
"Hello!"
end
end
jimmy = Person.new
jimmy.say_hello # "Hello!"
class Person
end
Person.instance_eval do
def human?
true
end
end
Person.human? # true
class Greeting
def method_missing(sym, *args, &block)
puts "#{sym} was called with #{args} and #{block.call}"
end
end
Greeting.new.hello("world") { p "bye!" }
defined? var_name
# nil or true
obj = String.new
if obj.respond_to?(:program)
obj.program
else
puts "Sorry, the object doesn't understand the 'program' message."
end
By Datt Dongare
Meta programming in ruby
I've expertise in web development using Ruby on Rails and ReactJS. I help teams to write better code and also mentor them for organizing the projects efficiently