Skip to content

Instantly share code, notes, and snippets.

@ariera
Created September 24, 2012 09:23
Show Gist options
  • Save ariera/3775101 to your computer and use it in GitHub Desktop.
Save ariera/3775101 to your computer and use it in GitHub Desktop.
An example of mixins in Rails

With this you can do

Restaurant.all_with_photo #=> will return all the restaurants with a photo
User.first.photo_width #=> 65px
Restaurant.first.photo_url #=> "http://......"
class Restaurant < ActiveRecord::Base
include WithPhoto
end
class User < ActiveRecord::Base
include WithPhoto
end
module WithPhoto
def self.included(base)
base.send :extend, ClassMethods
base.send :include, InstanceMethods
end
module ClassMethods
# this is where you have to write all your static methods
def all_with_photo
# retrive all the instances with a photo
end
end
module InstanceMethods
# this is where you write your instance methods
def photo_url
#retrive the url for the photo
end
def photo_width
####
end
def photo_height
####
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment