### rails dev general notes * models are always capitalized singular (db tables created in plural) * controllers are capitalized plural, CamelCase (due to Ruby classes) * use symbols since they are basically hash keys in rails * table names are symbols * use `bundler` to update gems for application * Don't forget JS runtime (execjs, node.js, etc.) * When generating a controller, rails can take multiple view names after controller name * gems can be built using "--without production" for rails specific environments * "actions" are methods specified during controller creation * when using rspec, make sure environment is correct in spec/spec_helper.rb * run all rspec tests by specifying directory versus page.rb * when named routes are created, they follow the convention "blah_path" * db migrations default with "change" method. removing columns requires methods "up" or "down" * always run rake db:migrate after changes to migrations * ActiveRecord handles Object methods instead of "raw" ruby code (i.e. attr_accessor, etc) * strong parameters allow objects to be instantiated with required and/or permitted values (raises forbidden attribute error) * rendering doesn't count as another request, error messages displayed with flash may persist - use flash.now (flash is a hash which takes a symbol argument) * update_attribute(s) = allows for updating of data without validation * cookies rails object is a hash which uses a "value" key with its data; also has "expires" key which can be used to dictate length of cookie cookies[:remember_token] || cookies[:remember_token] = {value:,expires:} * cookies.permanent automatically sets an expiration date of 20 years from issue = cookies.permanent[:remember_token] = remember_token * cookies.delete(:var) = used to remove cookies from browser * before_ actions can also be placed in controller code; before_ applies to each action (method) in controller code, therefore actions can be 'restricted' * rails automatically creates .tableName? checks on models based upon empty/non-empty values * params hash is built from variables submitted to controller from page (form page, method actions, etc) ### routes stuff * run rake routes to see "prefix", e.g. signup and append "_path", e.g. signup_path * paths can take arguments * use _path in views and _url in controllers ### useful `rails`, `rake`, and bundle commands rails server --environment blah = starts a rails server with specified environment rails generate controller NaMes action1 action2 options = Generate a new controller with slave actions (views are created as well) rails generate model Name table:type table:type = Generate a new model (db table) with columns and their type(s) rails generate integration_test controller_pages = Generates rspec tests in spec/requests/controller_name.spec.rb rails generate migration add_index_to_tableName_column = Generates a migration based on adding an index to a table's column rails generate migration add_columnName_to_tableName columnName:type = adds a new column to the db rails destroy controller|model NaMe|Name (action1 action2) = Completely remove a controller/model and its slave content (bundle exec) rake db:migrate = used when changes to the db have been made (bundle exec) rake db:migrate RAILS_ENV=environment = apply db changes to specific environment (consult config/database.yml for live applications) (bundle exec) rake db:rollback = undo a single migration (bundle exec) rake db:migrate VERSION=n = rollback db to specific version (use 0 for beginning) (bundle exec) rake db:reset = start db over from scratch (including resetting 'id' table(s)) rake routes = shows how routes map out via routes.rb bundle exec rspec spec/requests/blah.rb = use rspec TDD with tests located in blah.rb ##### asset pipelines * rails =< 3.0 stored assets in public{/stylesheets,/javascripts,/images} and were served as http://blah/stylesheets|images, etc. * rails >= 3.1 stores assets in {app lib vendor}/assets app/assets = assets specific to present application lib/assets = assets for libraries written by dev team vendor/assets = assets from third party vendors ####### web design specifics * div classes map to CSS identifiers starting with "#" * partials should be used when sharing views with multiple controllers; use link 'shared/blah' (app/views/shared)'; file name starts with _ (rails specific) * app/assets/stylesheets = asset pipeline; any stylesheets located here are automatically included as part of 'application.css' * use app/views/layouts/application.html.erb for dynamic 'static' items such as title * html5 shim: * /*...*/ = CSS comment * periods "." before a name in CSS signifies a class, e.g. ".center" *
= indicates that elements go at the top of the page *
= divides document into distinct parts; older HTML uses
for almost all site divisions *
    = unordered list *
  • = list item ###### css syntax name { / item: value; / } ##### rails helpers * app/helpers/application_helper.rb = use as a skeleton for static entries, e.g. titles, etc. By default these are not available within controllers, only views use include "SomethingHelper" within controller code ##### rails syntax erb|html * <%= link_to "Name", 'URL', 'options_hash' %> = provides an HTML link to content; third option is optional * <%= link_to image_tag("path", 'options_hash') 'URL' %> = provides an HTML image link; default path is app/assets/images/ (asset pipeline) * <%= provide(var, 'name') %> = provides data * <%= yield(var, 'name') %> = replaces content with items supplied by yield * <%= render 'layouts/shim' %> = renders HTML from app/views/layouts/_shim.html.erb; _blah is a rails convention that helps identify partials * comments can be inserted by placing '#' after the percent sign * <%= debug(params) if Rails.env.blah? %> = prints debugging information to screen via erb * <%= form_for(@object) do |x| block ... end %> = creates a form for creating specified object where "x" is x.attribute (e.g. x.email, x.name, etc.) * <%= form_for(:resource, url: resource_path) do |x| block ... end %> = used when there is no data model (db table) to interact with; uses routes :resource * <%= pluralize(blah_integer, "some message") %> = inflection method which automatically pluralizes second argument based upon first integer argument * <% flash.each do |k,v| %> = use flash hash to display messages; use with content_tag for cleaner HTML * <%= content_tag(:div, v, class: "blah-#{k}")%> = use erb to produce a div based upon the key and value (k, v) from a flash hash * flash hash from bootstrap gem includes :error (red), :success (green), and :notice (yellow) #### form helpers http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html ##### rspec syntax * ensure config.include Capybara::DSL is included in spec/spec_helper.rb for syntax below * "something" is intended for human readers let(:var) { "something" } = preference of local variable vs. instance variable subject { page } = subject can be anything, including an instance variable describe "blah" do block end before { visit n_path } = runs code in block prior to further tests click_link "link URL" expect(page).to have_content|title|selector, etc. it { should|should_not have_content('some text..') } it { should|should_not have_title('something...') } it { should|should_not have_selector('html tag', text: 'blah') } it { should|should_not respond_to(:ModelColumn) } = ruby Object method .respond_to? it { should|should_not be_valid } = rspec way of writing @blah.valid? shared_examples_for "something" do \ some tests using syntax \ end = provide some standardized tests it_should_behave_like "something" = utilize shared test above within particular check ######## migration code * database-specific syntax is used here, create table, drop table, etc. * string = think small varchar types * text = think larger varchar types * integer = integer types * float = floating point numbers (decimals) * datetime & timestamp = complete timestamps in column * binary = storing binary data (images, video, sound, etc.) * boolean = true or false types (1 or 0, on or off, etc.) * rails specific column enforcement types * limit (:limit => "n") * default (:default => "blah") * null (:null => true|false) false is NOT NULL * tables can be automatically populated in migration code AFTER creation/update/etc. via block * table names should ALWAYS match controller name, but in plural! * migrations can specify the use of the key 'default:' to set initial values (other than nil) * add_index :tableName, :columnName, unique: true = adds a unique enforcement on the table; run rake db:migrate afterwards * add_column :tableName, :columnName, :type = adds a column to the table with type * has_secure_password in model code combines "older" methods password and password_confirmation (which check matches and .authenticate method) password_digest column MUST be present ### rails console specifics # Reference model and controller code for correct variables testuser = CwaJobHistory.find_by_jobid(...), etc. * look at models for creation, e.g. user = User.current; user = CwaIpaUser.new * default environment is development * --sandbox = starts console in sandbox * can specify environment from start, e.g. `rails console production` * Rails.env.environment? = boolean value on environment check * Rails.env = prints current environment * Model.errors = get error messages (e.g. with save errors) * Model.errors.full_messages = 'cleaner' output ####### creation process without using scaffolding 1.) rails new /path/to/app_name -d dbase_server (rails 4.x automatically runs `bundle install` after creation of standard content) 2.) use bundler to install gems required by the app (`bundle install`) 3.) edit database.yml to suit needs 4.) rails generate (rails 4.x) script/rails generate model Blah (can do multiple models) 5.) rails generate (rails 4.x) script/rails generate migration table_name (should be plural, can do multiple tables) 6.) rake db:migrate (each environment if need be) 7.) rails generate (rails 4.x) script/rails generate controller Blah (can do multiple controllers) ######## model code * associations are like key restraints in SQL for linking data * associations use has_one, has_many, belongs_to, has_and_belongs_to_many * ensure that singularity/plurality is reflected for model * associations allow for sharing of object (table row) data via method grouping, i.e. @row1.row2.row2_data * validation code goes within model code; check api.rubyonrails.org * ensures that db column types are respected * before_save { self.colum = column.downcase } = as stated before saving, downcase column data * as in ruby, modules are "included"'ed into a class definition versus a "require" of a file ##### controller code * controllers (methods) deal with user requests/inputs * controllers can be seen as URL's, /list, /delete, etc. * controller methods take "params" data from views or actions * controller methods use the convention Controller.method (Book.find, Subject.find, etc.) * db specific methods, .save (saves row to table), .update_attributes (updates row), .destroy (deletes row from table) * controller find methods must use ID only, no other fields are valid * when using strong paramenters use syntax params.require(:blah).permit(:blah,:blah,etc) # views/template (erb) code * directory is created based upon model generation in app/views/blah * erb code is placed within specific template directory, with name reflecting controller methods * view code should have block implemented when passing data to a method, i.e. a block for "id => ", etc. * use link_to blah for displaying row data on URL * method (instance) variables can be assigned from param[:foo] values # basic form code * form_tag :action => 'method' do = signifies beginning of input form to be passed to specific controller method * pulling data to populate page requires previously defined method (i.e. 'edit') which form_tag :action uses to post to another method (i.e., 'update') * text_field 'object', 'field' = signifies text field associated with object for specific field * can use text_area as well * radio_button 'object', 'field', value (0|1 for boolean) = uses a radio button to set a specific value