Created
July 7, 2011 18:25
-
-
Save dbrady/1070178 to your computer and use it in GitHub Desktop.
Get ActiveRecord object from object_or_id argument
This file contains hidden or 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
class StoreProductCollaborator | |
def initialize(product_or_id, store_or_id) | |
# I use this pattern everywhere. I would like to abstract it, but | |
# can't think of a good name for the abstraction. | |
@product = Product.find(product_or_id) unless product_or_id.is_a? Product | |
@store = Store.find(store_or_id) unless store_or_id.is_a? Store | |
end | |
# Intended usage examples: | |
# sp1 = StoreProductCollaborator.new(42, 13) | |
# sp2 = StoreProductCollaborator.new(@product, @store) | |
# sp3 = StoreProductCollaborator.new(42, @store) | |
# sp4 = StoreProductCollaborator.new(@product, 13) | |
# ...I can even see the shape in my mind of this code, and its | |
# value as an abstraction: if we called it foo_snark(klass) and put | |
# it on Integer AND on ActiveRecord::Base, then Integer could find | |
# the object, and ActiveRecord::Base could check to make sure that | |
# the AR object given matches the expected class. | |
# | |
# But seriously, what to call it? instantiate? to_model? | |
# to_model_instance? | |
end |
jtanner: nevermind, you said the thing I asked apparently I can't read.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@dbrady: Surely the former. I am constantly astonished at the variety of foolishness available. ;>