Skip to content

Commit

Permalink
- Added the "Monkey Patching" facility on DynamicProperties, along wi…
Browse files Browse the repository at this point in the history
…th tests to ensure it works as advertised.

- Added a quick example script.
  • Loading branch information
Richard Clayton committed Sep 20, 2011
1 parent 983b901 commit 06d28ba
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
20 changes: 20 additions & 0 deletions dynamic_properties.rb
Expand Up @@ -130,6 +130,9 @@ def method_missing(name, *args)
if property_name.nil?
super
else
# Monkey Patch the property so the next
# call doesn't go "missing"
self.patch_property property_name
# if we are dealing with a getter
if mode == :getter
if @properties.has_key? property_name
Expand All @@ -145,5 +148,22 @@ def method_missing(name, *args)
end
end

# Monkey patch the existing class to have
# the property (thereby not incurring the
# overhead of a method_missing call)
# @param method_name [String] name of the method
# to add to the class.
def patch_property(method_name)
self.class.class_eval %Q{
class #{self.class}
def #{method_name}
@properties['#{method_name}']
end
def #{method_name}=(value)
@properties['#{method_name}'] = value
end
end }
end

end
end
31 changes: 31 additions & 0 deletions examples.rb
@@ -0,0 +1,31 @@
require_relative 'dynamic_properties'
require "date"

class WeatherObservation
include Berico::DynamicProperties

def initialize
@date_time = ::DateTime.now
end

def to_s
output = "Weather Observation \n"
output << " Time: #{@date_time}\n"
@properties.each do |key, value|
output << " #{key}: #{value}\n"
end
output
end
end

observation = WeatherObservation.new

observation.temperature = 75
observation.dew_point = 25
observation.wind_speed = 10
observation.wind_dir = 270
observation.visibility = 10
observation.sky_con = :clear
observation.altimeter = 29.92

puts observation
28 changes: 28 additions & 0 deletions spec/dynamic_properties_spec.rb
Expand Up @@ -126,6 +126,34 @@ def initialize

end

context "monkey_patch" do

it "should create a new accessor and mutator for a property the first time it goes missing" do

richard_clayton = "Richard Clayton"

dp = BasicDynoClass.new
dp.name = richard_clayton

dp.methods.include?(:name).should == true
dp.methods.include?(:name=).should == true

dp.properties.length.should == 1
dp.properties["name"].should == richard_clayton
dp.name.should == richard_clayton

joe_black = "Joe Black"

dp.name = joe_black

dp.properties.length.should == 1
dp.properties["name"].should == joe_black
dp.name.should == joe_black

end

end

context "Validation Functions" do

it "should return whether a configuration hash is valid" do
Expand Down

0 comments on commit 06d28ba

Please sign in to comment.