Skip to content

Instantly share code, notes, and snippets.

@pbrisbin
Created May 23, 2013 13:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pbrisbin/5636088 to your computer and use it in GitHub Desktop.
Save pbrisbin/5636088 to your computer and use it in GitHub Desktop.
module AwesomeResource
def initialize(attributes = {})
attributes.each do |key,val|
sym = key.to_sym
reader = :"#{sym}"
writer = :"#{sym}="
unless respond_to?(reader)
self.class.send(:attr_reader, sym)
end
unless respond_to?(writer)
self.class.send(:attr_writer, sym)
end
send(writer, val)
end
end
end
describe AwesomeResource 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
@DNNX
Copy link

DNNX commented May 24, 2013

This is a bit shorter: https://gist.github.com/DNNX/5643769 .

I removed unnecessary conversion of strings to symbols and vice versa.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment