Skip to content

Instantly share code, notes, and snippets.

@sebabelmar
Last active April 13, 2016 04:28
Show Gist options
  • Save sebabelmar/5a70cea918b4d38576a9282679517bcf to your computer and use it in GitHub Desktop.
Save sebabelmar/5a70cea918b4d38576a9282679517bcf to your computer and use it in GitHub Desktop.

Ain't she sweet?!

Database Level

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.

Model level

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

Controller level

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)

View Level

erb is the most common templating use in DBC... but there are more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment