Skip to content

Instantly share code, notes, and snippets.

@jamesgary
Created May 23, 2013 21:23
Show Gist options
  • Save jamesgary/5639529 to your computer and use it in GitHub Desktop.
Save jamesgary/5639529 to your computer and use it in GitHub Desktop.
Method Modeling: A Refactoring: A Refactoring
module AwesomeResource
attr_reader :awesome_attributes
def initialize(attributes={})
@awesome_attributes = attributes
@awesome_attributes.keys.each do |method_name|
create_method(method_name.to_sym) do
@awesome_attributes[method_name]
end
create_method("#{method_name}=".to_sym) do |new_val|
@awesome_attributes[method_name] = new_val
end
end
end
private
def create_method(name, &block)
self.class.send(:define_method, name, &block)
end
end
describe 'something' do
it "creates readers and writers for any attributes passed in during initialization" do
article_class = Class.new do
include AwesomeResource
end
article = article_class.new("title" => "Fun")
article.title.should == "Fun"
article.title = 'Fun Times!'
article.title.should == 'Fun Times!'
expect { article.unknown_attribute }.to raise_exception
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment