Module: Peel::Modelable::ClassMethods

Defined in:
lib/peel/modelable.rb

Instance Method Summary collapse

Instance Method Details

#columnsObject



46
47
48
49
# File 'lib/peel/modelable.rb', line 46

def columns
  @repository.execute("PRAGMA table_info(#{@name})")
    .map { |col| col[1].to_sym }
end

#create_accessorsObject



26
27
28
29
30
31
# File 'lib/peel/modelable.rb', line 26

def create_accessors
  columns.each do |column|
    define_method("#{column}") { instance_variable_get("@#{column}")}
    define_method("#{column}=") { |value| instance_variable_set("@#{column}", value)}
  end
end

#find(id) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/peel/modelable.rb', line 33

def find(id)
  result = @repository.execute(
    "SELECT * FROM #{@name} WHERE id = ? LIMIT 1",
    id
  )
  if result.empty?
    {}
  else
    result_hash = columns.zip(result.first).to_h
    new(result_hash)
  end
end

#peel_off(table) ⇒ Object



20
21
22
23
24
# File 'lib/peel/modelable.rb', line 20

def peel_off(table)
  @name = table.to_s
  @repository = Repository.new
  create_accessors
end