Skip to content

Commit

Permalink
cache the property methods once they're called for the first time
Browse files Browse the repository at this point in the history
  • Loading branch information
kddnewton committed Apr 14, 2016
1 parent 7cc0310 commit c23c89f
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 6 deletions.
1 change: 1 addition & 0 deletions lib/humidifier.rb
Expand Up @@ -4,6 +4,7 @@
require 'humidifier/props'
require 'humidifier/fn'
require 'humidifier/ref'
require 'humidifier/property_methods'

require 'humidifier/aws_shim'
require 'humidifier/resource'
Expand Down
16 changes: 16 additions & 0 deletions lib/humidifier/property_methods.rb
@@ -0,0 +1,16 @@
module Humidifier
module PropertyMethods

def build_property_reader(name)
define_method(name) do
properties[name.to_s]
end
end

def build_property_writer(name)
define_method(name) do |value|
update_property(name.to_s[0..-2], value)
end
end
end
end
11 changes: 6 additions & 5 deletions lib/humidifier/resource.rb
Expand Up @@ -3,6 +3,7 @@ module Humidifier
# Superclass for all AWS resources
class Resource

extend PropertyMethods
attr_accessor :properties

def initialize(properties = {}, raw = false)
Expand All @@ -11,14 +12,14 @@ def initialize(properties = {}, raw = false)
end

def method_missing(name, *args)
sname = name.to_s

if !valid_accessor?(name)
super
elsif self.class.props.key?(sname)
properties[sname]
elsif self.class.prop?(name.to_s)
self.class.build_property_reader(name)
send(name)
else
update_property(sname[0..-2], args.first)
self.class.build_property_writer(name)
send(name, args.first)
end
end

Expand Down
2 changes: 1 addition & 1 deletion lib/humidifier/version.rb
@@ -1,3 +1,3 @@
module Humidifier
VERSION = '0.0.15'.freeze
VERSION = '0.0.16'.freeze
end
33 changes: 33 additions & 0 deletions test/property_methods_test.rb
@@ -0,0 +1,33 @@
require 'test_helper'

class PropertyMethodsTest < Minitest::Test
class Slate
extend Humidifier::PropertyMethods
attr_accessor :properties

def initialize(properties = {})
self.properties = properties
end

def update_property(key, value)
properties[key] = value
end
end

def test_build_property_reader
Slate.build_property_reader(:foo)
slate = Slate.new('foo' => 'bar')

assert slate.respond_to?(:foo)
assert_equal 'bar', slate.foo
end

def test_build_property_writer
Slate.build_property_writer(:foo=)
slate = Slate.new

assert slate.respond_to?(:foo=)
slate.foo = 'bar'
assert_equal 'bar', slate.properties['foo']
end
end

0 comments on commit c23c89f

Please sign in to comment.