Last active
January 2, 2016 01:19
-
-
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.
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
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 aSuperUser.wrap
method doesn't feel right either. Thoughts?