Class: RailsDb::Table

Inherits:
Object
  • Object
show all
Includes:
Connection
Defined in:
lib/rails_db/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Connection

#column_names, #column_properties, #columns, #connection, #to_param

Constructor Details

#initialize(table_name) ⇒ Table

Returns a new instance of Table.



17
18
19
20
21
22
# File 'lib/rails_db/table.rb', line 17

def initialize(table_name)
  throw 'Access Denied' unless RailsDb::Database.accessible_tables.include?(table_name)
  @name = table_name
  @data = RailsDb::TableData.new(self)
  self
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



8
9
10
# File 'lib/rails_db/table.rb', line 8

def data
  @data
end

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/rails_db/table.rb', line 8

def name
  @name
end

Instance Method Details

#add_ransack_methods(klass) ⇒ Object



73
74
75
76
77
78
79
80
81
# File 'lib/rails_db/table.rb', line 73

def add_ransack_methods(klass)
  klass.define_singleton_method(:ransackable_attributes) do |auth_object = nil|
    column_names.map(&:to_sym)
  end

  klass.define_singleton_method(:ransackable_associations) do |auth_object = nil|
    []
  end
end

#as_modelObject



69
70
71
# File 'lib/rails_db/table.rb', line 69

def as_model
  @model ||= create_model(name)
end

#create_model(table_name, &block) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/rails_db/table.rb', line 49

def create_model(table_name, &block)
  begin
    klass = Class.new(ActiveRecord::Base) do
      def self.model_name
        ActiveModel::Name.new(self, nil, table_name)
      end
      self.table_name = table_name
      self.inheritance_column = nil
    end
    klass.count # verify that it works, if not load other, hack
  rescue
    klass = ActiveRecord::Base.descendants.detect { |c| c.table_name == table_name }
  end

  add_ransack_methods(klass) if ransack_version >= Gem::Version.new('4.0.0')
  klass.class_eval(&block) if block_given?

  klass
end

#delete(id) ⇒ Object



45
46
47
# File 'lib/rails_db/table.rb', line 45

def delete(id)
  RailsDb::Database.delete(name, primary_key, id)
end

#indexesObject



33
34
35
# File 'lib/rails_db/table.rb', line 33

def indexes
  RailsDb::Database.indexes(name)
end

#primary_keyObject



41
42
43
# File 'lib/rails_db/table.rb', line 41

def primary_key
  RailsDb::Database.primary_key(name)
end

#ransack_versionObject



83
84
85
# File 'lib/rails_db/table.rb', line 83

def ransack_version
  Gem.loaded_specs['ransack'].version
end

#to_csvObject



24
25
26
27
28
29
30
31
# File 'lib/rails_db/table.rb', line 24

def to_csv
  CSV.generate do |csv|
    csv << column_names
    data.data.rows.each do |row|
      csv << row
    end
  end
end

#truncateObject



37
38
39
# File 'lib/rails_db/table.rb', line 37

def truncate
  RailsDb::Database.truncate(name)
end