0

One of my classes called global_list is being overgrown and I'd like to break it out to a module called GlobalListAggregate. There are a set of find_by_sql methods that I'd like to use (yes, I'll refactor later) but need to move them out of global_list first.

I'd like something like (obviously are sql queries are much more complex than this):

module GlobalListAggregate < ActiveRecord::Base
  def self.get_users
    sql="select * from users"
    users=find_by_sql([sql])
  end
end

but a module can't be extended this way. How could I achieve this?

thx

timpone
  • 17,029
  • 31
  • 103
  • 200

3 Answers3

0

A popular pattern in Rails is "concerns," which are basically modules that extend ActiveSupport::Concern, which adds some syntactic sugar for making this sort of thing (especially defining class methods on the extended class) a little easier. The documentation at that link, as well as the answers to this SO question are pretty instructive.

Community
  • 1
  • 1
Jordan Running
  • 91,621
  • 15
  • 164
  • 165
  • thx; Funny, I'm reading this right now about concerns: http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns . I could see something be desgined towards that at a later point but I'd really like to slim down these models (slimming in just the loc per .rb file) – timpone Nov 18 '13 at 20:33
0

I don't really understand Concerns yet, so the other answer may be best, but I was going to say that if I understand your objective correctly, you should be able to do:

module GlobalListAggregate
  def get_users
    sql="select * from users"
    users=find_by_sql([sql])
  end
end

and then add extend GlobalListAggregate in your GlobalList class.

Peter Alfvin
  • 26,897
  • 7
  • 60
  • 98
  • I was thinking of doing that way but we really want to seperate it out from the idea of the class GlobalList since it doesn't really have the attributes of the GlobalList class (global_id / list_id) - just an array of them. But perhaps, what you're thinking is the best way. Probably, it's more me not wanting to see these `find_by_sql` statements in this class than anything else. – timpone Nov 18 '13 at 20:40
  • As defined, `GlobalListAggregate` is _not_ related to `GlobalList` except via its name, which you can of course change to whatever you want. – Peter Alfvin Nov 18 '13 at 20:44
0

assuming your usage is something like this

GlobalListAggregate.get_users.each { |user| puts user.id }

this is a bit of a cheat, not sure If I recommend it

module GlobalListAggregate 
  def self.klass
    User
  end

  def self.get_users
    sql="select * from users"
    klass.find_by_sql([sql])
  end
end 
house9
  • 19,614
  • 8
  • 52
  • 60