Created
September 29, 2011 07:32
-
-
Save LichP/1250189 to your computer and use it in GitHub Desktop.
Ohm::Model.const_missing using eval instead of const_get
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'ohm' | |
module SomeNamespace | |
class Post < Ohm::Model | |
attribute :title | |
attribute :body | |
collection :comments, Comment | |
end | |
class Comment < Ohm::Model | |
attribute :body | |
reference :post, Post | |
end | |
end | |
@post = SomeNamespace::Post.create(:title => "Latest Blog", :body => "Lorum ipsum dolor sit amet") | |
@comment = SomeNamespace::Comment.create(:body => "Blah blah waffle", :post => @post) | |
@post.comments << @comment | |
@post.save | |
puts @post.comments.all |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'ohm' | |
module SomeNamespace | |
class Post < Ohm::Model | |
def self.const_missing(name) | |
wrapper = Wrapper.new(name) { eval(name.to_s) } | |
# Allow others to hook to const_missing. | |
begin | |
super(name) | |
rescue NameError | |
end | |
wrapper | |
end | |
attribute :title | |
attribute :body | |
collection :comments, Comment | |
end | |
class Comment < Ohm::Model | |
attribute :body | |
reference :post, Post | |
end | |
end | |
@post = SomeNamespace::Post.create(:title => "Latest Blog", :body => "Lorum ipsum dolor sit amet") | |
@comment = SomeNamespace::Comment.create(:body => "Blah blah waffle", :post => @post) | |
@post.comments << @comment | |
@post.save | |
puts @post.comments.all |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment