Module: Applicat::Mvc::Model::Resource::Base

Included in:
Area, Organization, Profession, User
Defined in:
lib/applicat/mvc/model/resource/base.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/applicat/mvc/model/resource/base.rb', line 6

def self.included(base)
  base.class_eval do
    #has_many :role_assignments, :class_name => 'Role', :as => :authorizable
    
    cattr_reader :per_page
    @@per_page = 20
  
    attr_accessor :current_user
      
    if self.table_exists?
      
      columns.map(&:name).select{|c| c.match('_id')}.each do |column|
        association = column.split('_id').first.classify
        
        define_method "#{association.underscore}_name" do
          self.send("#{association.underscore}").try(:name)
        end
        
        accessible_attributes << "#{association.underscore}_name"
        
        define_method "#{association.underscore}_name=" do |name|
          return if name.blank?
          
          association_type = association
          
          if self.class.columns.map(&:name).include?("#{association.underscore}_type")
            association_type = self.send("#{association.underscore}_type")
          end
          
          begin
            association_type = association_type.constantize
          rescue
            association_type = self.class.reflections[column.split('_id').first.to_sym].options[:class_name].constantize
          end
           
          self.send("#{association.underscore}=", association_type.find_or_initialize_by_name(name))
        end
      end
    end
    
    #def role_for?(role_name, user)
    #  return true if new_record?
    # 
    #  role_assignments.joins(:users).where('roles.name = ? AND users.id = ?', role_name, user.id).any?
    #end
      
    def to_s
      self.name rescue self.class.name.humanize
    end
  end
end