· 9 years ago · Jan 31, 2017, 09:02 AM
1#!/usr/bin/env ruby
2require 'sqlite3'
3require 'rubygems'
4require 'thor'
5require 'highline'
6require './property.rb'
7require 'securerandom'
8def db_connect
9 @db = SQLite3::Database.new "test.db"
10 @db.results_as_hash = true
11 @db.execute "CREATE TABLE IF NOT EXISTS Properties(Id TEXT PRIMARY KEY ,
12 Title TEXT,
13 Property_type TEXT,
14 Address TEXT,
15 Nightly_rate_in_EUR REAL,
16 Max_guests INTEGER,
17 Email TEXT,
18 Phone_number TEXT)"
19 @db
20end
21
22class ThorRubyCli < Thor
23 desc "new" ,"new"
24 def new
25 property = Property.new(id: SecureRandom.hex(10).to_s.upcase!)
26 puts "Starting with new property #{property.id}."
27 input_params(property)
28 end
29
30 desc "continue" ,"continue"
31 def continue(prop_id)
32 property = Property.find(prop_id)
33 return if property.nil?
34 puts "Continuing with property #{property.id}"
35 input_params(property)
36 puts "Great job! Listing #{property.id} is complete!"
37 end
38
39 desc "list" ,"list of properties"
40 def list
41 props = Property.list
42 puts "No properties found." if props.to_a.empty?
43 props.each do |prop|
44 puts "#{prop['Id']} : #{prop['Title']}"
45 end
46 end
47
48 private
49
50 def input_params(property)
51 cli = HighLine.new
52 validate_hash = Property.validate_hash
53 property.instance_variables.each do |var|
54 if property.instance_variable_get(var).nil? || property.instance_variable_get(var).to_s.empty?
55 property.instance_variable_set(var, cli.ask(Property.question(var)) { |q| q.validate = validate_hash[var] })
56 property.save
57 end
58 end
59 end
60end
61
62$db = db_connect
63ThorRubyCli.start