front and back-end web development, Leeds, UK


Richard's Blog - Design, coding and life in Japan

Richard

Using an alias method with an abstract class model in Ruby on Rails

I was surprised about how easy and nice this solution was, I needed a separate model to manage 2 different kinds of sessions in my rails project. A regular user session and a cart specific user session. I don't know if this is the best way to organize my data but it is a legacy system that is built that way!
class UserSession < ActiveRecord::Base
abstract_class = true
set_table_name "sessions"

def add key, val
user_session = find_key key
if user_session.blank?
user_session = UserSession.new
user_session.session_id = @session_id
user_session.key = key
user_session.value = val
user_session.save
else
user_session = self.find_key key
user_session.update_attributes({:value=>val})
end
end

end
Then in my cart session method I just inherit the User Session class and create the alias method over-riding it with any cart session specific session info I have
class CartSession < UserSession
alias_method :orig_add, :add

def add key, val
orig_add("cart_"+key, val)
end

end
This is too nice!

Tags:

Recent Blog Posts