views:

15

answers:

1

I am looking to replicate a given object function across various model files

As you can see below, the 2 things I need to vary across the model are

1) the "guser" string 2) the self.xxx

SIMPLIFIED CODE SAMPLE:

  def self.get_all
       statement="SELECT * FROM gusers WHERE"
       results = results + self.find_by_sql(["#{statement} #{statements[shard_id]}"])
       return results
  end

It would be great if you can provide code to help out here - thanks!

+1  A: 

you can create a module like this (suggesting gusers is the table to the current model)

module SharedFunctions
  def self.get_all
    statement = "SELECT * FROM #{self.table_name} WHERE"
    #... I don't understand what you wanne do here
  end
end

And than in you models:

class SomeModel < ActiveRecord::Base
  include SharedFunctions
end

UPDATE:

But what I really would do would look like this:

module SharedFunctions
  def self.get_all
    self.all :conditions => ...
  end
end

More information about Conditions can be found here: http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Or even better you can use scopes:

class SomeModel < ActiveRecord::Base
  named_scope :get_all, :conditions => ...
end
jigfox
so i would define table_name in each model?
ming yeow
no, it's already there sponsored by the rails developers (http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002286)
jigfox
thanks a lot! named_scope looks awesome but we are sharding our DB (hence losing a large part of the rails coolness), so the module idea looks like it will work the best
ming yeow