Sha256: e4332a8376d8fb28195ae3ed0ca6c62bb138c757ae6d52d29b9649205fe0b8bd

Contents?: true

Size: 1.66 KB

Versions: 4

Compression:

Stored size: 1.66 KB

Contents

module RailsDb
  class TableData
    include Connection
    include TablePagination

    attr_reader :table, :time
    attr_accessor :current_page, :offset, :per_page, :sort_column, :sort_order, :select_columns

    delegate :each, :to => :data
    delegate :count, :to => :table

    def initialize(table)
      @table = table
    end

    def data
      @data ||= begin
        commands = []
        if select_columns && select_columns.any?
          commands.push("SELECT #{select_columns.join(', ')} FROM #{table.name}")
        else
          commands.push("SELECT * FROM #{table.name}")
        end
        if sort_column
          commands.push("ORDER BY #{sort_column} #{sort_order}")
        end
        if per_page
          commands.push("LIMIT #{per_page.to_i} OFFSET #{offset.to_i}")
        end
        results, @time = Database.adapter.exec_query(commands.join(' '))
        results
      end
    end

    def limit(limit)
      self.per_page = limit
      self
    end

    def desc
      self.sort_order = 'desc'
      self
    end

    def asc
      self.sort_order = 'asc'
      self
    end

    def order_by(column)
      self.sort_column = column
      self
    end

    def order(sort_order)
      self.send(sort_order) if [:asc, :desc].include?(sort_order.to_sym)
      self
    end

    def select(*select_columns)
      self.select_columns = Array.wrap(select_columns).flatten
      self
    end

    def columns
      if select_columns && select_columns.any?
        select_columns
      else
        table.column_names
      end
    end

    def count
      Database.adapter.exec_query("SELECT COUNT(*) FROM #{table.name}")[0].rows.flatten.last.to_i
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rails_db-0.6 lib/rails_db/table_data.rb
rails_db-0.5.1 lib/rails_db/table_data.rb
rails_db-0.5 lib/rails_db/table_data.rb
rails_db-0.4 lib/rails_db/table_data.rb