Ruby: Beyond the Basics
          by Michael Koby
      http://www.codecasts.tv
Hi, my name is...
 Michael Koby
@mkoby
http://www.codecasts.tv
http://www.mkoby.com
What
What


•   Open Classes
What


•   Open Classes

•   Dynamic Methods
Metaprogramming Ruby
       by Paolo Perrotta

O’Reilly: http://obyk.us/39267
Amazon: http://obyk.us/1efe7
Open Classes
What is an “Open Class?”
You’ve Heard
   of this by
Another Name
Monkeypatching
class String
  #shortened for brevity

  def sub(a, b)
    #replaces string ‘a’ with string ‘b’
  end

  def gsub(a, b)
    #similar to sub but with the /g from RegEx
  end

  #shortened for brevity
end
class String
  def to_alphanumeric
    gsub /[^ws]/, ‘’
  end
end
1.9.3 :005 > “my string”.methods.grep /alphanumeric/
=> [:to_alphanumeric]
class Employee
  def salary
    “Some Number”
  end
end
class Employee
  def salary
    “Some Number”
  end
end

class Employee
  def name
    “Some Name”
  end
end
e = Employee.new
e = Employee.new

e.salary
e = Employee.new

e.salary   # => “Some Number”
e = Employee.new

e.salary   # => “Some Number”

e.name
e = Employee.new

e.salary   # => “Some Number”

e.name     # => “Some Name”
class Employee
  def salary
    “Some Number”
  end
end

class Employee
  def name
    “Some Name”
  end
end
Some Real Life Samples
Dynamic Methods
How You Usually Call Methods
someObject.methodName
Dynamically Calling Methods
x = 2
x = 2

x.send(:+, 2)
x = 2

x.send(:+, 2)   => 4
class APIRequestWrapper
  attr_accessor :client

  def initialize
    @client = Savon::Client.new do |wsdl|
      #wsdl.options go here
    end
  end

  ## Makes API request, request_name is string
  ##     parameters is a Ruby hash
  def make_api_request(request_name, paramenters)
     @client.request(request_name.to_sym) do |soap|
       soap.body = parameters
     end
  end
end
Some Real Life Samples
In Closing...
Open Classes
class Employee
  def salary
    “Some Number”
  end
end

class Employee
  def name
    “Some Name”
  end
end
Dynamic Methods
x = 2

x.send(:+, 2)   => 4
Metaprogramming Ruby
       by Paolo Perrotta

O’Reilly: http://obyk.us/39267
Amazon: http://obyk.us/1efe7
Thank You!

Ruby: Beyond the Basics