Skip to content

Instantly share code, notes, and snippets.

@adamhunter
Last active January 2, 2016 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamhunter/8229357 to your computer and use it in GitHub Desktop.
Save adamhunter/8229357 to your computer and use it in GitHub Desktop.
wrapping an ActiveRecord instance in a subclass with more functionality. Given an instance you didn't create (aka current_user, User class), you can get a new instance who's class is the wrapping class. The primary reason to do this is for smaller objects in different parts of your system.
# per sean cribb's suggestion some time ago
User.new.becomes(Super::User) # thanks Rails :)
# below not needed, for reference
User = Class.new(ActiveRecord::Base)
class Super::User < ::User
def self.wrap(user)
new.init_with 'attributes' => user.attributes, 'column_types' => user.class.column_types
end
def make_me_a_sandwich
open('http://imgs.xkcd.com/comics/sandwich.png')
end
end
require 'open'
user = User.first
sudo = Super::User.wrap(user)
sudo.make_me_a_sandwich
@adamhunter
Copy link
Author

I'm curious on thoughts about this pattern. Normally I feel like I would just cram the extra functions in module MakeMeASandwich but that doesn't feel right. The fact that I had to write a SuperUser.wrap method doesn't feel right either. Thoughts?

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