Skip to content

Instantly share code, notes, and snippets.

@jimytc
Last active August 22, 2018 08:25
Show Gist options
  • Save jimytc/ecea8c2aad885420ee4c443bca3c7306 to your computer and use it in GitHub Desktop.
Save jimytc/ecea8c2aad885420ee4c443bca3c7306 to your computer and use it in GitHub Desktop.
ActiveRecord::Schema.define do
create_table :posts do |table|
table.string :title
table.string :content
end
end
class Post < ActiveRecord::Base
end
class LazyObject
class ObjectNotFoundError < StandardError; end
def initialize(klass, id_or_object)
@klass = klass
case id_or_object
when ActiveRecord::Base
@object = id_or_object
when Integer, String
@id = if @klass.columns_hash['id'].type == :integer
id_or_object.to_i
else
id_or_object.to_s
end
else
raise ArgumentError.new("The second argument should be object of ActiveRecord::Base or id of that #{klass}")
end
end
def object
@object ||= @klass.find_by(id: @id)
@object or raise ObjectNotFoundError
end
def id
@id ||= object.id
end
def method_missing(method, *args, &block)
object.send(method, *args, &block)
end
def respond_to_missing?(method, include_private = true)
super || object.respond_to?(method, include_private)
end
end
# Suppose we've got 1,000 posts in the database.
# id: 10, title: 'post 10', content: 'hello world * 10'
# id: 11, title: 'post 11', content: 'hello world * 11'
lo = LazyObject.new(Post, 10)
puts lo.id
puts lo.title
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment