module MotionRecord::Persistence::ClassMethods

Public Instance Methods

create(attributes={}) click to toggle source

Create a new record

attributes - a Hash of attribute values

Returns the created record

# File lib/motion_record/persistence.rb, line 74
def create(attributes={})
  record = self.new(attributes)
  record.save
  record
end
primary_key() click to toggle source

Sybmol name of the primary key column

# File lib/motion_record/persistence.rb, line 81
def primary_key
  :id
end
table_columns() click to toggle source
# File lib/motion_record/persistence.rb, line 90
def table_columns
  unless @table_columns
    @table_columns = get_columns_from_schema.each_with_object({}) do |column, hash|
      hash[column.name] = column
    end
    @table_columns.values.each do |column|
      define_attribute_from_column(column)
    end
  end
  @table_columns
end
table_name() click to toggle source
# File lib/motion_record/persistence.rb, line 85
def table_name
  # HACK: poor-man's .pluralize
  self.to_s.downcase + "s"
end

Protected Instance Methods

define_attribute_from_column(column) click to toggle source

Interal: Set up setter/getter methods to correspond with a table column

# File lib/motion_record/persistence.rb, line 111
def define_attribute_from_column(column)
  # TODO: handle options
  define_attribute column.name, default: column.default

  if TIMESTAMP_COLUMNS.include?(column.name)
    serialize column.name, :time
  end
end
get_columns_from_schema() click to toggle source

Internal: Fetch column definitions from the database

# File lib/motion_record/persistence.rb, line 105
def get_columns_from_schema
  pragma_columns = connection.execute "PRAGMA table_info(#{table_name});"
  pragma_columns.map { |p| Schema::ColumnDefinition.from_pragma(p) }
end