Skip to content

Instantly share code, notes, and snippets.

@LichP
Created September 29, 2011 07:32
Show Gist options
  • Save LichP/1250189 to your computer and use it in GitHub Desktop.
Save LichP/1250189 to your computer and use it in GitHub Desktop.
Ohm::Model.const_missing using eval instead of const_get
#!/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
#!/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