root/trunk/lib/use_find_helpers.rb

Revision 1251, 2.0 kB (checked in by gaspard, 2 months ago)

commit 6842d0e7e87fe09360327cc73d795ce083d02f51
Author: Gaspard Bucher <gaspard@teti.ch>

Simplified zena customization (adding new models). Just drop a plugin inside 'vendor/plugins'. All models defined in the 'models' folder will be loaded.

Line 
1 module Zena
2   module FindHelpers
3     module UseFindHelpers
4       # this is called when the module is included into the 'base' module
5       def self.included(base)
6         # add all methods from the module "AddActsAsMethod" to the 'base' module
7         base.extend Zena::FindHelpers::TriggerClassMethod
8       end
9     end
10    
11     module ClassMethods
12       def fetch_ids(sql, id_attr='id')
13         unless sql =~ /SELECT/i
14           sql = "SELECT `#{id_attr}` FROM #{self.table_name} WHERE #{sql}"
15         end
16         connection.select_all(sql, "#{name} Load").map! do |record|
17           record[id_attr.to_s]
18         end
19       end
20
21       def fetch_list(sql, *attr_list)
22         unless sql =~ /SELECT/i
23           sql = "SELECT #{attr_list.map {|a| "`#{a}`"}.join(', ')} FROM #{self.table_name} WHERE #{sql}"
24         end
25         connection.select_all(sql, "#{name} Load").map! do |record|
26           Hash[*(attr_list.map {|attr| [attr, record[attr.to_s]] }.flatten)]
27         end
28       end
29
30       def next_zip(site_id)
31         res = connection.update "UPDATE zips SET zip=@zip:=zip+1 WHERE site_id = '#{site_id}'"
32         if res == 0
33           # error
34           raise Zena::BadConfiguration, "no zip entry for (#{site_id})"
35         end
36         rows = connection.execute "SELECT @zip"
37         rows.fetch_row[0].to_i
38       end
39
40       def fetch_attribute(attribute, sql)
41         unless sql =~ /SELECT/i
42           sql = "SELECT `#{attribute}` FROM #{table_name} WHERE #{sql}"
43         end
44         row = connection.execute(sql).fetch_row
45         row ? row[0] : nil
46       end
47     end
48    
49     module TriggerClassMethod
50       def use_find_helpers
51         class_eval <<-END
52           include Zena::FindHelpers::InstanceMethods
53           class << self
54             include Zena::FindHelpers::ClassMethods
55           end
56         END
57       end
58      
59       # ...
60     end
61    
62     module InstanceMethods
63       # ...
64     end
65   end
66 end
67
68 ActiveRecord::Base.send :include, Zena::FindHelpers::UseFindHelpers
69 ActiveRecord::Base.send :use_find_helpers
Note: See TracBrowser for help on using the browser.