The skeletton that we used today has a connection on config/database.rb
to a posgress DB if there is not set by ENV variable:
db = URI.parse(ENV['DATABASE_URL'] || "postgres://localhost/#{APP_NAME}_#{Sinatra::Application.environment}")
In that same file you can see that we set:
DB_NAME = db.path[1..-1]
Having that ENV variable then we can use it in the Rakefile. Besides using this file to execute task you can see the database name printed in the console thanks to:
desc "Create the database at #{DB_NAME}"
task :create do
puts "Creating database #{DB_NAME} if it doesn't exist..."
exec("createdb #{DB_NAME}")
end
If you do:
rake -T
Once having the name of the DB (ex. your_root_folder_development) you can go and open the PSQL CLI.
psql your_root_folder_development
In there use your SQL magic to inspect tables \dt or select * from <your_table>;
to see all fields and entries.
In model you can add extra behavior to the class that maps the SQL table in ruby like:
class Word < ActiveRecord::Base
# Remember to create a migration!
# At this level you can add validation, associations, custom validations and more...
# callback
before_create do
sorted_version = self.word_input.chars.sort.join
self.word_sorted = sorted_version
end
# extra chimichangas
def
Word.where(word_sorted: self.word_sorted)
end
end
There is a mantra in web development that chants:
'Keep your your controllers thin and clean' - Sam Dud
Thanks to the Sinatra Skeleton magic localed in config/database.rb
we have access to the models inside the controllers:
Dir[APP_ROOT.join('app', 'models', '*.rb')].each do |model_file|
filename = File.basename(model_file).gsub('.rb', '')
autoload ActiveSupport::Inflector.camelize(filename), model_file
end
Be careful the way you manage your get
and post
requests and 'p' params all the time (in other words, log).
Use @variables
only when needed (make that variable accesible in the view)
erb is the most common templating use in DBC... but there are more.