Module: ActsAsTableless::ActiveRecordMethods

Defined in:
lib/acts_as_tableless.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_tablelessObject



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
57
58
59
60
# File 'lib/acts_as_tableless.rb', line 7

def acts_as_tableless
  class << self
    def table_name
      self.name.tableize
    end

    def columns()
      @columns ||= [];
    end

    def column(name, sql_type = nil, default = nil, null = true)
      columns << ActiveRecord::ConnectionAdapters::Column.new( name.to_s, default, sql_type.to_s, null )
    end

    def columns_hash
      @columns_hash ||= Hash[columns.map{|column| [column.name, column]}]
    end

    def column_names
      @column_names ||= columns.map{|column| column.name}
    end

    def column_defaults
      @column_defaults ||= columns.map{|column| [column.name, nil]}.inject({}){|m, e| m[e[0]] = e[1] ; m}
    end

    def descends_from_active_record?
      true
    end
    
    def all
      ActsAsTableless.class_variable_get(:"@@#{self.name.underscore}")
    end
    
    def find(id)
      ActsAsTableless.class_variable_get(:"@@#{self.name.underscore}").select{|record| record.id == id}.first
    end
    
    def delete(ids)
      ids = [ids] unless ids.is_a?(Array)
      # this coule be improved
      ids.each do |id|
        find(id).delete
      end
    end
    
    def exists?(id)
      find(id).nil? ? false : true
    end
  end
  ActsAsTableless.class_variable_set(:"@@#{self.name.underscore}", [])
  ActsAsTableless.class_variable_set(:"@@#{self.name.underscore}_increment", 1)
  include InstanceMethods
end