
front and back-end web development, Leeds, UK
Richard's Blog - Design, coding and life in Japan
Using an alias method with an abstract class model in Ruby on Rails
Submitted by Richard on Sat, 10/17/2009 - 14:24I 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
- Testing controllers in Lithium 2nd Feb 12, 18:19
- Practical Internationalization in Lithium 31st Dec 11, 02:06
- Using OAuth in Lithium 30th Dec 11, 23:47
- How to add your own Tokens from CCK fields in Druapl 7 17th Jun 11, 04:49
- Weaving Lithium #li3 into a legacy PHP application incrementally 5th Oct 10, 11:54