Skip to content

Instantly share code, notes, and snippets.

@jplong91
Last active April 24, 2021 22:04
Show Gist options
  • Save jplong91/4ee8eb001d9ddba1013399fcc2bb9d1f to your computer and use it in GitHub Desktop.
Save jplong91/4ee8eb001d9ddba1013399fcc2bb9d1f to your computer and use it in GitHub Desktop.
Today I Learned...

TIL - Today I Learned

Wednesday, 11/20/19

Explaining require and permit: params.require(:person).permit(:name, :age)

The params in a controller looks like a Hash, but it's actually an instance of ActionController::Parameters, which provides several methods such as require and permit.

The require method ensures that a specific parameter is present, and if it's not provided, the require method throws an error. It returns an instance of ActionController::Parameters for the key passed into require.

The permit method returns a copy of the parameters object, returning only the permitted keys and values. When creating a new ActiveRecord model, only the permitted attributes are passed into the model.

It looks a lot like the whitelisting that was formerly included in ActiveRecord models, but it makes more sense for it to be in the controller.


Monday, 10/28/19

Ruby has a method .advance(days: 1) which interacts with time based objects to advance/decrement time. Use this to interact better with Dayling Saving Time issues that may come up.


Friday, 9/13/19

ActiveRecord Rails Object.find(ids) works! You can pass an array of ids to .find and all the records will be grabbed.


Thursday, 9/12/19

Ruby Throw double colon :: before a class to sometimes address undefined class errors. The :: colon tells rails to search outside of its normal scope


Monday, 7/29/19

Saw some interesting behavior when using .map(&:name) vs .pluck(:name) with regards to test data. At first I was setting up test data using build(:meal)... and my map was working, while pluck was erroring out all over the place. However, when I switched the data setup in the test suite to create(:meal), the pluck started to work! But why?

My understanding - pluck makes a query at the database level, but because build doesn't create the database object until it's needed, no record existed in the database at the time of the pluck. Using create solved the problem because that creates the database record upon creation.

map, operates on Ruby objects, not at the database level, so the whole record(s) is pulled, then the array of records is iterated on. Because of this, map demanded object creation in a different way than pluck, so build worked for map, because map wasn't communicating directly with the db!


Wednesday, 7/17/19

In Ruby, when discarding arguments, the convention is to use an underscore, like (underscore)ingredients. But you can even just turn it into (asterisk underscore).


Friday, 7/12/19

Ruby is faster than ActiveRecord chains for small sized datasets. This article helps layout some target methods to look out for when used on ActiveRecord::Relations because they may be slow: https://www.speedshop.co/2019/01/10/three-activerecord-mistakes.html


Wednesday, 7/10/19

Flexbox css is amazing. Make the parent container display: flex and use flex attributes on children. &:last-of-type { marging-right: 0; } is a sass css way to use flexbox so that there is no margin/padding on the left and right sides of the children (so there is only even spacing between them, but the full container's width is utilized).


Monday, 6/17/19

FactoryBot don't care. If you are trying to set an attribute on a class, as long as that class has a setter (doesn't really matter how it got there), FactoryBot will just use it

thing = Thing.new
thing.send(#method, args)  #=> kinda what under the hood looks like

Friday, 6/7/19

git show <commit id> shows the diff for a particular commit

Don't trust .first, .second, etc, in rspec when calling on objects, because they may not be in the same order when ActiveRecord is doing its jig


Monday, 5/20/19

Ruby has a safe navigation operator &., that will return nil instead of a no method error if the object doesn't exist...

photo = photo.find_by(category)  #=> lets say this doesn't find anything, so it returns nil

photo.asset  #=> this would return a nil class error if photo doesn't exist when we try to call asset

photo&.asset  #=> returns nil if photo doesn't exist, or returns the photo's asset if it does :thumbs_up

Thursday, 5/2/19

const works as it would appear in JS when used on primative datatypes - strings, booleans, integers. /facepalm on this one. It's only with objects, such as arrays, that the object is actually mutable. You just can't change the datatype in that case.


Wednesday, 4/23/19

In Linux based systems you can type: file path/to/file in the terminal to see a files char type (UTF-8 for example)


Monday, 4/21/19

Rspec - instead of using create you can use attributes_for to return just a hash of all the fields on an object, instead of an object.


Friday, 4/17/19

In Ruby, inject is the same thing as reduce


Thursday, 4/16/19

Ruby has these mini-class objects called Structs that... well, act like sub-classes.

  MealVariant = Struct.new(:meal, :ingredients_assignments, :has_options)
  
  Once built, it holds onto its components and you can call them using:
  
  MealVariant.meal => gives you the meal you stored.

Thursday, 4/4/19

Calling instance methods on initialize works - this implies that the class is built even before intialization happens.


Friday, 3/22/19

Ruby - .each loop sorts normally, whatever order the things that are being eached on, will stay the same. However, .find_each sorts things in batches (default batch size is 1000) to conserve memory. But what's really cool, is that .find_each sorts objects by ID, which it needs to work internally. Shyea.


Thursday, 3/21/19

Ruby (correction, Rails) has a method .squish which trims all excess whitespace, and newline characters from a string, and returns the string with each 'word' separated by a space. This is similar to strip which is a Ruby method that removes excess whitespace at the beginning and end


Monday, 3/18/19

In the mac terminal, source (file to reload) re-sources the particular file. (reloads)


Saturday, 3/16/19

In the mac terminal, the command 'mv' is used to move files from one directory to another. For example

ls
# file.txt project0

mv file.txt project 0

ls
# project0

cd project0
ls
# file.txt

to zip files, or compress, in the terminal, use this command: zip -r (desired filename).zip (folder file is in, or filename by itself)


Friday, 3/15/19

Bullet is a ruby gem that helps catch N+1 queries and places where eager loading isn't used. What are N+1 queries...? PUT SOME STUFF HERE FUTURE JOHN


Tuesday, 3/12/19

Sublime shortcuts -

CMD + K, CMD + B toggles the file navigation sidebar

CMD + W closes current file


Thursday, 2/28/19

Exclusive OR. (XOR). Exclusive OR only outputs true when the two booleans being compared are different (one is true the other is false). In ruby the operator for this is the caret - ^. In plain english - you only get one option or the other. Not both, and not neither.

true_thing ^ false_thing  #=> true
false_thing ^ false_thing  #=> false
true_thing ^ true_thing  #=> false (normal OR statement would evaluate to true here)

Friday, 2/22/19

Ruby '.each_with_object' iterates over a collection, passing in the current element and a object (that continues to be built). Super useful for building up hashes

array = ['foo', 'bar']
array.each_with_object({}) do |ele, hash|
  hash[ele] = ele.upcase
end
=> { 'foo' => 'FOO', 'bar' => 'BAR' }

git clean -fd removes untracked files and directories


Thursday, 2/21/19

GC.stat - in rails console to look at garbage collector stats

Ruby/Rails '.pluck' selects only targeted attributes from an active record query and returns those in an array

User.pluck(:name)  #=> let's pretend we have 3 users
=> ["Joe", "Bob", "Tom"]  #=> instead of other attributes tacked on like ID, address, email, etc

Wednesday, 2/20/19

sudo !!  #=> re-runs the last command with sudo

"rake stats" gives breakdowns for various rails filetypes by line counts, test relationships and more. A useful little look into the broad stats of a codebase.


Tuesday, 2/19/19

'grep' in termainal can be used to search files for occurances of whatever keyword you want

grep "Hello" app/models/HelloWorld"
=> returns lines where "Hello" was found in the targeted file

Thursday, 2/14/19

Keyword arguments in Ruby. A good way to make arguments for methods more clear

def entry(greeting:, planet: 'Earth')
  puts greeting
  puts planet
end

entry(greeting: 'hello', planet: 'world')

This can make method parameters much easier to parse at a glance, and also supports defaults


Monday, 2/11/19

http://www.betterspecs.org/

Rspec

  • create: an object is created that also persists in the database. model and database validations are triggered
  • build: builds an object but does not save it to the database. validations are only run for associated objects
  • build_stubbed: no database call is made. a fake id and created_at are made, but no validations are run

Friday, 2/8/19

ADD MORE HERE Inverse of


Thursday, 2/7/19

Triple bang exits all binding.pry instances

!!!

Tuesday, 2/5/19

In the RSpec testing framework, you can run a specific test from the command line but amending the line number the test starts on to the test file... like so:

rspec /some/folder/file.rb:25

This would run the spec file at the specified location starting on line 25


Friday, 1/25/19

Ruby has an operator that looks like this:

a ||= b

which is shorthand for this:

a || a = b

It means, if a is undefined or falsey (false or nil), then evaluate b and set a to the result. So:

a  #=> undefined
b = 'something special'

a ||= b  #=> 'something special'
a  #=> 'something special'

Monday, 1/21/19

Rails scope. Using scope, one can delineate a subset of data from the whole and access this set of data later in the object. Like so -

Class Pie
  scope :meat, -> { where(has_meat: true) }
 # more stuff
end

# sometime later
Pie.meat.each do

This allows usage of certain data that have already been somewhat sorted for you - rather than making a SQL query.


Wednesday, 1/16/19

In JS, to create an immutable variable for a value (not a datatype as the keyword const does), use:

let iDontLikeChange = Object.freeze(*insert stuff here*)  // to create an immutable variable

Tuesday, 1/15/19

Typing 'history' in the terminal gives you a list of the commands you've used since having the terminal open


Tuesday, 12/18/18

Why doesn't Ruby support method overloading? Methods can be overloaded (same name, different signature) in other languages. This assumes the signatures are different by either having arguments with different data types (one: int, two: int) v. (one: string, two: string), or a different number of arguments. While Ruby can have a different number of arguments, this would inheritly not work, because Ruby will not know what method to call given the lower argument option.

So, the real reason is because Ruby does not declare method input variable types


Monday, 12/17/18

Apache Spark - data processing library used for many purposes

  • Architecture: Driver coordinates the work, doesn't actually do the work. Driver watches the cluster manager which splits up the work into clusters. HERE uses YARN for cluster management (master-slave relationship). YARN manages the resources allocation (who gets how much CPU power, etc).
  • Spark has optimizations which make code and data more compact and run with less memory

Project idea: Spark configuration calculator


Friday, 8/23/18

Scala map v. flatMap. As we know, a map takes a list and applies a function to each element in that list. Sometimes that function also returns a list, so we end up with lists (the new lists for each element) within a list (the original)

something.map(ele => List(ele - 1, ele, ele + 1))
result #=> List(List(eleA - 1, eleA, eleA + 1), List(eleB - 1, eleB, eleB + 1), List(eleC - 1, eleC, eleC + 1), etc)

a flatmap flattens the results into one list (the original list) so the output of the previous problem would be

something.flatMap(ele => List(ele - 1, ele, ele + 1))
result #=> List(eleA - 1, eleA, eleA + 1, eleB - 1, eleB, eleB + 1, eleC - 1, eleC, eleC + 1)

Sometimes having items in just one list can be more useful!


Wednesday, 8/21/18

SAT: System Acceptance Test

PAT: Performance Acceptance Test

When using git, to reset a single file back to the HEAD, use

git checkout HEAD -- nameOfFile.txts

Monday, 8/19/18

Comments in code, what's a good rule of thumb? Today I heard something I like - if your comments need to say what your code is doing, your code could probably be broken up (or put together) to be more implicit. Instead comments should focus on why you're doing something!


Sunday, 8/18/18

In Javascript's newest form (ES6) there is something perhaps unintuative at first that works for creation of constansts. Check this out:

const LANGUAGES = ['Js', 'Ruby', 'Python', 'Go'];
LANGUAGES = "Javascript"; // shows error.
LANGUAGES.push('Java'); // Works fine.
console.log(LANGUAGES); // ['Js', 'Ruby', 'Python', 'Go', 'Java']

Here's the explanation from the blogpost I took the code from - Consider in this way. Whenever you define a const variable, Javascript references the address of the value to the variable. In our example the variable ‘LANGUAGES’ actually references to the memory allocated to the array. So you cannot change the variable to reference some other memory location later. Throughout the program it only references to the array.

So basically, when defining a constant you can't change to where that constant points in memory, it will always point to (in this case) that array. However it's perfectly OK to add more to that array, the variable will still point to the spot in memory that the array is at...


Monday, 8/13/18

AWS Lambda is serverless computing... meaning, you don't have to manage server space for processing of data. Lambda handles all server related components that run in the background.

VPC, as it relates to AWS, stands for virtual private cloud.


Wednesday, 8/8/18

Protocol Buffers (Protobuf) - Is a method of communication (think JSON) between programs. Invented by Google, protobufs are known for their speed and efficiency. Protobuf is a little less readable than JSON for humans, but can make up for the simplicity with efficiency.


Monday, 8/6/18

When using Vue, you can use v-on:submit.prevent=submit() as a way to submit a login request


Sunday, 7/29/18

In Object Oriented Programming, polymorphism is an important concept to understand. Polymorphism relates to inheritence, in that, a child class can have a method with the same name and functionality as the parent class, but the method in the child class will take precedence. For example:

a Shape class has a draw() method inside of it
the Circle class inherits from the Shape class, so it to has a draw() method
the Circle class implements its own draw() method because drawing a circle is different than drawing another shape...

In fact, is it in possible to draw() a shape? Not really, because a shape is an abstract concept...

Thursday, 7/26/18

JSON stands for JavaScript Object Notation HOCON stands for Human Optimized Configuration


Tuesday, 7/17/18

A good way to save a piece of changes you made that you don't necessarily want to use right now, with git, is to create a branch. When you branch off master however, note that you still need to add and commit the changes to save them inside the branch. Then you can switch back to master, and reset to origin/master if applicable, to get back on the normal track, while your other changes live on the branch that was created.


Monday, 7/16/18

MD5 hexadecimal format is a sort of encoding method that I used for an API request parameter. An MD5 hash is an encoded chunk of something (in this case a timestamp + api_key). It looks like just a bunch of letters and numbers.


Thursday, 7/12/18

You can use git clean to discard changes that are in untracked locations.

git clean -f
git clean -fd   #=> to also remove directories

git clean -f removes all files that are untracked. To also remove directories (folders) use git clean -fd


Friday, 7/6/18

I spoke with a coworker today to learn about method overloading. Method overloading involves creating multiple methods with the same name that all take in different data types. This can be useful, for example, if you want to format a date. You may have the date as a timestamp, a long, a string, etc, but either way you want it formatted to the same thing. You can overload a method (use the same name multiple times) to accomplish this. Then when the method is called, the language will choose the correct method to use based on input data type.

def formatDate(inputDate : String) : String = {<put logic here>}
def formatDate(inputDate : Long) : String = {<put logic here>}

Monday, 7/2/18

Rails has predefined symbols for http request happy/sad paths. This can be found: http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option


Monday, 6/25/18

Useful application for countering null pointer exceptions. Any time you call a 'dot' something on a null value and error will be thrown that shuts down the application. This is cumbersome. To avoid this when comparing something with a potential null value to a string, ask if the string is equal to the value instead of a value equal to a string. For example

POTENTIALLY PROBLEMATIC
v.validationType.equals("PIPELINE")  #=> validationType is null an error will be thrown

YODA SPEAK THAT SOLVES PROBLEM
"PIPELINE".equals(v.validationType)  #=> "PIPELINE" the string can never be null because it's been defined right here!

Friday, 6/22/18

Amazon Redshift "databases" shouldn't be thought of as databases. It's super slow to do joins and things of that nature that you would do to normal databases. Instead think of Redshift databases like a file structure, where each table is a file. Because of this, if changes are made, it's conventional to make temp tables where changes are made, then completely delete and reupload the temp table into the production version. This delete/reupload process takes milliseconds. Redshift is good for extremely large datasets (datawarehouses) but is not a relational database and shouldn't be thought of as one.


Thursday, 6/21/18

In scala, you can call on the value of a key/value pair by using underscores... you can also use this call on things similarly for sizes greater than key/value pairs

val some_map = [key: "value"]
some_map._2  #=> will use 'value'

Tuesday, 6/19/18

Scala has the ability to let you put @tailrec before a recursive function, to bail out of the recursive backend part -> on the way out after you've already done all the logic work.

@tailrec
final def buildCityList(rs: ResultSet, cities: List[string]): List[String] = {
  rs.next() match {
    case false => cities
    case true => {
      val updatedCities = cities :+ rs.getString(1)
      buildCityList(rs, updatedCities)
    }
  }
}

Sunday, 6/17/18

In gists when writing code in backticks, you can select the coding language that will be applied by putting the language right after the backtick.

Some terminal commands

echo 'something' adds things to a particular file
echo hello >> test.txt

cat 'filename' shows what is inside the file

Friday, 6/15/18

Javascript has a useful operator -> '...' This operator can do a couple things, but I used it to spread an array used in a function call. Here's the example

BEFORE
cities.sort((cityA, cityB) => {
  let dates = getDatesToCompare(cityA, cityB);
  return isNewer(dates[0], dates[1]) ? -1 : 1;
});

AFTER
cities.sort((cityA, cityB) => return isNewer(...getDatesToCompare(cityA, cityB)) ? -1 : 1

When you're unable to run a java file to start a server and the error aligns something with "server already running" - check the task manager for apache instances running as well as terminals that are running and close them appropriately.


Monday, 6/11/18

Been a little while... not that I haven't been learning lots, but busy with work!

The power of git never ceases to amaze. Today I used git add --patch to add only certain hunks of a file. When you patch a file, git is smart enough to break the file down into hunks then gives you several options for adding (or not adding) those hunks. Here are some of those options spelled out:

y - stage this hunk for the next commit
n - do not stage this hunk for the next commit
q - quit: do not stage this hunk or any of the remaining hunks
a - stage this hunk and all later hunks in the file
d - do not stage this hunk or any of the later hunks in the file
s - split the current hunk into smaller hunks
e - manually edit the current hunk

This would make a good blog topic John


Thursday, 5/24/18 (self.happyBirthday)

In scala functions are defined in more than one way. For example, a function can be defined using val or def. In val the function is evaluated when defined. In def the function is evaluated on every call...

val test: () => Int = {
  val r = util.Random.nextInt
  () => r
}
test()
// Int = 3525
test()
// Int = 3525
#=> SAME THING!

def test: () => Int = {
  val r = util.Random.nextInt
  () => r
}
test()
// Int 2348
test()
// Int 9027
#=> NEW RESULT

Wednesday, 5/23/18

Scala has a .flatten method that turns an array of arrays into a single array.


Wednesday, 5/16/18

Git fetch - finds changes others may have made to the master codebase since you've started making your changes, however, it doesn't actually attempt to merge or rebase those changes. This way, you get a diff view of what has been added and can, if needed, prematurely resolve merge conflicts that may occur with a git pull.


Wednesday, 5/9/18

Scala enforces the presence or absence of something by using an Option. For example...

val a = Array(3, 5, 9, 2, 1)

a.find(_ < 4)  #=> Option[Int] = Some(3)

a.find(_ > 10)  #=> Option[Int] = None

An underscore in Scala represets 'any number'


Monday, 5/7/18

Lessons learned (the nice way). With a user input box on a webpage, the user could if they were mean, enter scripts or JS commands that would then run as html when the page loads. To combat this, web developers have to enact some amount of security - one such way is to render the '<' & '>' as plain text...

Command line - git bash. When making a commit message... using single quotes '' instead of double quotes "" lets you hit enter without submitting the commit. This lets you write the commit message on multiple lines and only the enter after the closing quote will submit the commit.


Tuesday, 5/1/18

I started to dig up information about whether Ruby was compiled or interpreted, meaning, is the code converted to machine code on runtime, or compiled beforehand and run separately... the jist, is that Ruby is interpreted, but I was able to discover quite a bit more about the process Ruby uses to turn the 'programmer code' into machine code.

  • The Ruby interpreter first tokenizes the programmer code into more structured computer data
# Example string
"a = 1"

# Tokenized
["a", "=", "1"]
  • Ruby then uses lexing to add more data to the tokens, it looks a bit more complicated
[[[1, 0], :on_ident, "a"],
[[1, 1], :on_sp, " "]
[[1, 2], :on_op, "="]
[[1, 3], :on_sp, " "]
[[1, 4], :on_int, "1"]]
  • These are the first steps Ruby takes to break up the programmer code into chunks it can then use to parse.

  • Ruby can then take the parsed code and compile it to bytecode, which looks a lot like assembly code.

0011 putstring      "foo"
0013 leave
0014 pop
0015 putstring      "bar"
0017 leave

The Ruby VM then runs through these commands and executes them.


Friday, 4/27/18

In the process of completing a Java tutorial on Lynda.com (directed from the HERE workcenter website) that will be useful for my new position at HERE, I will be learning a TON. Learning Java has provided me with an insightful new perspective on code... I will probably make a blog post for this but I'll start compiling my information tid-bits here.

Java is, at its core, most useful for it's ability to be dynamic with regards to running on various operating system with ease. Java compiles code into bytecode which can then be transferred to virtually any OS where it is then converted into machine code (1's and 0's) for the computer to consume. This is different then something like C or C++ where the programmer's code is converting into machine code directly. Slightly more time consuming, but more dynamic are languages like Java.


Thursday, 4/26/18

Sublime shortcut - 'Ctrl + M' jumps to end (or starting) parantheses... 'Shift + Ctrl + M' highlights all text between this jump.

Some JS nonsense...

[] + [] = ""
[] + {} = [object Object]
{} + [] = 0
{} + {} = NaN

Thursday, 4/19/18

In RSpec, when using FactoryBot to create models... 'build' vs 'create'. Build makes a Ruby object but doesnt' save it to the database, create makes an object and saves it to the database.


Friday, 4/6/18

Javascript has a .trim() method that removes whitespace from a string.


Monday, 3/26/18

Arrow functions don't have their own this! They take the obj from outside of whatever they're in... ex:

let user = {
  firstName: "Ilya",
  sayHi() {
    let arrow = () => alert(this.firstName);
    arrow();
  }
};

user.sayHi(); // Ilya

This whole page is a TIL: https://javascript.info/object-methods regarding how this works in JS.

When writing tests, it's important to have your test(s) fail first, then succeed. If the test succeeds right away, and possibly all the time, then you may have a poorly written test.


Thursday, 3/22/18

With regard to inheritence, this refers to the object you're in...

Factory Bot creates fake data for testing. SimpleCov looks at your testing coverage (in Rails). Travis CI checks the test suite to see if something you wrote breaks another test.


Monday, 3/19/18

Ruby code etiquette: because Ruby functions, by default, return the last thing they ran, putting an early return indicates that you want to exit the function once a certain point is reached.


Friday, 3/16/18

In JavaScipt you can 'throw' objects, such as error messages, given certain conditions

DnaTranscriber.prototype.toRna = function(dna) {
  let pairs = { C: "G", G: "C", A: "U", T: "A" };
  let rna = "";
  dna.split("").forEach(function(nucl) {
    if (pairs[nucl]) {
      rna += pairs[nucl];
    } else {
      throw new Error("Invalid input");
    }
  });
  return rna;
};

In this example, if pairs[nucl] is falsey, we throw an Error that says "Invalid input".


Thursday, 3/15/18

Ruby has 'rescue' error handling that catches an error and renders whatever you put below the rescue. You can then also add an ensure after the rescue to run code that you want to run even in case of a failure

def mymethod
  "a"/0
  rescue Twilio::REST::RequestError => error
    "Your problem #{error}"
  ensure
    'do something else important'
end

Thursday, 3/8/18

In JS, or Ruby, you can set default values for arguments inside the parameters parantheses.

TwoFer.prototype.twoFer = (who='you') => `One for ${who}, one for me.`

or

TwoFer.prototype.twoFer function(who='you')

This means that if no parameter is passed, it will set a default for the argument.


Thursday, 2/22/18

Any time you are using a collection as successive arguments to some method, you can use the method method:

ALPHABET.all?(&phrase.downcase.method(:include?))

vs

ALPHABET.all? { |char| phrase.downcase.include?(char) }

In addition to allowing these transformations to be written in-line, method is slightly faster than an explicit loop, and also saves on having to come up with good variable names. It also tends to be shorter than the equivalent loop.


Tuesday, 2/20/18

The splat operator in Ruby has a lot going on... For one, the splat operator can be used as a catch-all for varying amounts of arguments

def go(x, *args)
  puts args.inspect
end

go("a", "b", "c")

Instead of typing everything here, check out: http://blog.honeybadger.io/ruby-splat-array-manipulation-destructuring/ for more information


Thursday, 2/15/18

To create a snip screenshot on mac, 'cmd + shift + 4'. A full screenshot is 'cmd + shift + 3'.


Wednesday, 2/14/18

While experimenting with the ternary operator in Ruby ( a ? b : c ) instead of if statements, I found that you couldn't 'return thing' like normal. Instead, put the 'return thing' in paranthesis, like so (return thing). Example:

strand.chars.map do |c|
  if DNA_RNA_MAPPING.has_key?(c)
    DNA_RNA_MAPPING[c]
  else
    return ""
  end
end.join

# Instead Becomes
strand.chars.map { |l| RNA_Pairs.has_key?(l) ? RNA_Pairs[l] : (return '') }.join

The line of code above that I wrote may be the best line of code I feel that I've written yet! strand.chars.map is a great way to take in a string and transform it into another string!


Tuesday, 2/13/18

Don't forget about .reverse() in JS. Simply reverses all of the items in an array.


Monday, 2/12/18

In Ruby, the method: 'rstrip' removes white spaces or extra lines from the end of a string.

names = ["Linda\n", "Tom\n"]
names.rstrip  #=> returns ["Linda", "Tom"]

Sunday, 2/11/18

This is awesome. In Ruby, you can set extra constraints for your arguments of a function. To do this, you 'raise' an 'ArgumentError.new'. You can even add a message about why the argument(s) are invalid.

if a.length != b.length
  raise ArgumentError.new('Argument lengths are not the same!')
end

Saturday, 2/10/18

Ruby contains a '.zip' method, which can combine two arrays, pairing up values at equal indexes.

a1 = ['G', 'A', 'C']
a2 = ['G', 'T', 'T']
pairs = a1.zip(a2)
  #=> pairs would be [['G', 'G'], ['A', 'T'], ['C', 'T']]

This continues to work with other interesting combinations of zips. For example you can combine 3+ arrays similarly as well.


Friday, 2/9/18

In Ruby to make strings longer or shorter... Shorter:

str_var.slice(1..10)

Longer:

str_var.ljust(10, ' ')

Where, in both cases, str_var is the string in question. 'ljust' sets the length to the first argument


Tuesday, 2/6/18

In Ruby, '.pop' removes the last element in an array

array = ["a", "b", "c"]
array.pop  #=> returns "c"

Monday, 2/5/18

In JS, Math.abs(number) gives the absolute value of a number.


Saturday, 2/3/18

Testing controllers in rspec with params looks like this:

get :index, :params => { :location_search => "Chicago" }

Friday, 2/2/18

JS has a 'concat' method which merges two arrays, preserving item order

var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];

console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]

Thursday, 2/1/18

Similar to parseInt(), number.toString() changes an integer into a string in JS.

Some sorting in JS -

numbers = [5, 4, 2, 2, 1]

numbers.sort(function(a, b) { return a - b })  #=> Ascending order sort

numbers.sort(function(a, b) { return b - a })  #=> Descending order sort

OR

numbers.sort()  #=> Ascending order sort

numbers.sort().reverse()  #=> Descending order sort

Wednesday, 1/31/18

In JS, parseInt(numberInString) turns a number that's in a string into an integer. Ex:

strArray.forEach(function(num) {
	sum += parseInt(num);
});

Tuesday, 1/30/18

To exit VIM (opens sometimes after git pull) hit ':' then type 'q!'


Monday, 1/29/18

In JS, Math.round() is potentially needed more often than in Ruby, because (string.length / 2) will land on a decimal, whereas in Ruby you will be returned a whole number.


Sunday, 1/28/18

JS '.join' method combines an array of values and can take in a parameter to add something in between

array = ["J", "o", "h", "n"]
array.join("-")  #=> "J-o-h-n"

Wednesday, 1/24/18

When using Vue JS, specifically v-bind:style, the javascript that goes inside the quotes needs to also be in curly brackets. Only for style binds...

v-bind:style="{ margin: 0px }"

Tuesday, 1/23/18

Express JS (also known as just - express) is a framework for Node JS


Monday, 1/22/18

JS has a '.reload()' function built in that reloads the page.

location.reload() #=> reloads whatever the page you are currently on

Sunday, 1/21/18

Javascript has a 'replace' method, which allows you to replace a string with another string -

searchCardName = cardName.replace(" ", "%20")

This would replace all spaces - marked with " ", with "%20".


Wednesday, 1/17/18

Vue JS timing... run functions that need certain data immediately after that data has been acquired (running things right after they are configured in mounted)


Tuesday, 1/16/18

Modals, are similar to templates. They belong outside of certain elements and are then called on with buttons / anchor tags, etc.


Monday, 1/15/18

Adding a border to an object in CSS is a good way to see where the item is on the screen (what space it's taking up)


Sunday, 1/14/18

Jquery with $ before it can go in index.js in the Mounted area of whatever page it's on. Mounted represents things to run once the DOM is ready and loaded.

In Vue JS, put the most specific routes above the similar yet more vague routes

routes: [
    { path: "/", component: HomePage },
    { path: "/decks/create", component: CreateDeck },
    { path: "/decks/:id/edit", component: EditDeck },
    { path: "/decks/:id", component: SingleDeckPage },
    { path: "/decks", component: DecksPage },
    { path: "/teams/create", component: CreateTeam },
    { path: "/teams", component: TeamsPage },
    { path: "/login", component: Login },
    { path: "/signup", component: Signup },
    { path: "/card-search", component: CardSearch }
  ],

Saturday, 1/13/18

In CSS, you can link to an image using the background: url(link to file here) -

.mana {
  display: inline-block;
  background: url("../images/mana-symbols.png") no-repeat;
  color: transparent;
  width: 15px;
  height: 15px;
}

This follows a prompt similar to using the command line. In this case, it will move up one directory (folder) then dive one folder down into images where the mana-symbols.png file is located.


Thursday, 1/11/18

Django is the Python version of Rails... basically

'cmd + y' is an alternative to 'cmd + shift + z'

cd booklist && touch server.rb - runs both commands at once in the terminal


Wednesday, 1/10/18

In Rails you can create a dependancy deletion so to speak... it looks like:

class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
  validates :title, presence: true,
                    length: { minimum: 5 }
end

This 'dependent: :destroy' clause, says that if the 'article' instance is deleted, all comments in the database that belong to that article are also deleted. Pretty cool


Tuesday, 1/9/18

Working in branches in github - 'git branch branch-name' creates the branch


Monday, 1/8/18

Microservice v. Monolith

Monolith: This is where you're entire app runs within a singular... program. Everything is part of the same building (or monolith)

Microservice: App is broken down into pieces that communicate with each other. Those pieces may be in different programming languages, etc. This adds complexitity but can make it easier to work with as a team.

In Ruby, to find a key inside of a hash with a known value, you can use -

hash.key(value) #=> key

Sunday, 1/7/18

Test-Driven Development (TDD) cycle looks like: 'Write a test that fails' -> 'Make the code pass the test' -> 'Refactor the code'


Saturday, 1/6/18

Peter says, ~25% chance to be asked FIZZBUZZ question at interview


Friday, 1/5/18

TA Myles said that where he works (BCBS) they actually right the test for their code first, so the test fails, then they right their code so it passes the test. (Sunday look-back, this is TDD!)


Thursday, 1/4/18

RSpec is a Ruby gem that is used to 'test' your code. Testing code involves running tests to see if your code works and/or where it is breaking at.


Wednesday, 1/3/18

JS sort method in action:

let people = [
  { name: "Saron", age: 34 },
  { name: "Majora", age: 28 },
  { name: "Danilo", age: 45 }
];
console.log(people.sort((a, b) => a.age - b.age));

Tuesday, 1/2/18

Even more new, instead of 'require' you can say:

import variable_name from "file"

With Node, you can 'require' other files just like you would in Ruby.

Node.js, according to Peter, is basically another programming language. Node.js converts the JS that lives in the browser into JS that can manipulate and live on your computer instead.

Previously to debug things in JS, the developer would have to use 'alert' instead of console.log... yikes.


Wednesday, 12/27/17

In VueJS, something like v-bind is known as a directive. Directives are prefixed with a 'v-' to indicate that they are indicative to VueJS. Directives keep a property up-to-date on the DOM with what the current variable is in Vue's JS file.

Using .map in JS...

One way:

var numbers = [1, 2, 4, 2];

console.log(numbers.map(element => element * 2));

Second way:

var numbers = [1, 2, 4, 2];

console.log(
  numbers.map(function(element) {
    return element * 2;
  })
);

Explained: http://www.discovermeteor.com/blog/understanding-javascript-map/


Tuesday, 12/26/17

Some pre-built animations can be found at: https://daneden.github.io/animate.css/

VueJS can help control CSS animations by wrapping whatever it is you want to animate in a 'transition-group name='. This adds and removes classes when applicable and shows the linked CSS.

To make a string lowercase in JS...

var str = "Hello World!";
var res = str.toLowerCase();

Monday, 12/25/17

Merry Christmas


Sunday, 12/24/17

Happy Christmas Eve


Saturday, 12/23/17

Better remembering the reduce method in Ruby... numbers.reduce(initial value of thing being kept track of) { | thing being kept track of, individual element | process goes here }.


Friday, 12/22/17

Some regular expression shenanigans... when inside (), backslash always starts and ends the expression. so (/..../) is valid. However, additionally, forward slash 'b' - \b is used to say "start of a word" and \b at the end says "end of a word". So the \b's basically separate words.


Thursday, 12/21/17

Modals can be used in place of a 'show' page... Uses one less template in HTML/VUEjs


Wednesday, 12/20/17

When making a new model within a new model in a controller action... you can call on something from the previous model with a '.' instead of a : symbol.

card = Card.new(
      api_rf: params[:api_rf],
      name: params[:name],
      mana_cost: params[:mana_cost],
      card_type: params[:card_type],
      image_url: params[:image_url]
    )
    if card.save
      deck_card = DeckCard.new(
        deck_id: params[:deck_id],
        card_id: card.id,                <-------
        quantity: params[:quantity]
      )

Tuesday, 12/19/17

Vue.js has 'Lifecycle Hooks' meaning timing is an issue, things happen before or after other things. Instead of 'mounted' you can make a created hash which will happen before mounted...


Monday, 12/18/17

Regular expressions are sort of a way to compare a string or set of strings to something... for example:

address = "665 Clinton Lane, Wilkes Barre, PA 18702"
p address.gsub(/[0-9]/, '_')

The .gsub method, replaces all /items here/ with - 'new item'


Sunday, 12/17/17

You can send something to the front end, from the back end, by including it in the as_json. Usually if it's an easy true/false or something of that nature. This way you don't save 'useless' info into the back end, but the front end can use the value as if it was in the database. as_json is the bridge between the front and back end.

In JS, when referencing 'this', if you're inside of a function, you need to '.bind(this)' right after the function so that the function can see the proper 'this'.


Saturday, 12/16/17

Vue.js has special watcher processes, and can run functions from the frontend without calling them. Vue knows when you've updated a variable within the function and will run it appropriately.


Friday, 12/15/17

In Rails, in the seeds file, you can Thing.create multiple times, or, preferrably send an array of items, just once, and rails knows to create each one.


Thursday, 12/14/17

Previously when making websites, developers would employ separation of concerns meaning, HTML in one file, JS in another, CSS in another, etc. Now-a-days, we make web applications not websites so the relationships are more intertwined then they used to be and the concerns are not quite as... separated.

You can 'hard reload' a webpage (because the browser stores information so it doesn't need to be reloaded), by inspecting the page, then 'right-clicking' the reload button to 'hard reload'.


Wednesday, 12/13/17

In sublime, 'cmd + k' skips one when doing 'cmd + d' to select multiple of the same thing


Tuesday, 12/12/17

To make the linter ignore a variable in Sublime, you can create a JS comment like:

/* global variable_name */

Template tag in HTML goes after . It doesn't initially do anything but it exists there to be used by JS.

Making a web request in JS is called an AJAX (Asynchronous JS and XML).


Monday, 12/11/17

If it pleases you, JS and CSS can be editted in an html file. do basic js in script tags and css in style tags - not recommended to do in your html file anyways

document in html - magic

The DOM (Document Object Model) is build by the browser when a web page is loaded. The root element of the DOM comes from the written HTML.


Sunday, 12/10/17

JS Falsey conditions indclude: false, 0, "" (emtpy string), null, undefined, NaN (1/0).


Saturday, 12/9/17

In JS, an if statement requires the condition to be inside of parentheses

In Sublime, Ctrl + Cmd + G is similar to Cmd + D but it highlights everything that is the same at once.


Friday, 12/8/17

In JS, NaN stands for: Not-a-Number, and indicates that a value is a not a legal number.


Thursday, 12/7/17

When installing things via the terminal, if any permission errors occur, use sudo as a prefix to whatever you type in to run it as an admin. You will still need the computer password

Bootstrap Items

Carousel - a slideshow component for showing images

Card - think card... a flexible tool with many different looking configurations for storing information about a particular item in a small container

Modal - goes on top of everything else in the body. Prevents scrolling, instead the scroll will scroll through the modal. The user clicking on the 'backdrop' gets rid of the modal


Wednesday, 12/6/17

a kumquat is a tiny sour orange

In sublime, when writing HTML, one easy shortcut looks like - div.class_name or div#id_name

div.class_name (+ tab) #=> <div class="class_name"> </div>
div#id_name (+ tab)    #=> <div id="id_name"> </div>

Ruby spaceship operator (<=>) - https://i.stack.imgur.com/CpwOf.jpg. As used in sort, simply compares two numbers and assigns the relationship between the numbers as -1, 0 or 1. If the relationship is represented by a 1, Ruby switches the places of the two numbers. Otherwise it leaves them alone.

4 <=> 5  #=> assigned value of -1, so the items stay where they are in the array
5 <=> 4  #=> assigned value of 1, so sort will switch places of the items

Tuesday, 12/5/17

Using CSS: when setting colors with hexadecimal values - (#000). The first digit represents red, the second green, the third blue. The values go from 1-9, then a-f. So '#0f0' is bright green

database normalization is the process of breaking down big data and storing information across multiple tables.

SQL stands for structured query language


Monday, 12/4/17

When writing Ruby scripts, you can multiply strings to make that thing show up more than once...

"-" * 50
 #=> prints 50 '-'s

gem 'figaro' helps store API keys so that they are hidden in your ENV when posted online. (bundle exec figaro install) Instead of your api key in unirest requests, you use #{ENV['name of api key']} after it's saved in the proper spot.


Sunday, 12/3/17

Sorting Algorithms

There are also two subtypes of algorithms: stable and unstable. Stable sorts keep like elements in the same order as they were in, in the input array, preserving their order. Unstable sorts do not. This has implications for linked lists where you may want to keep like elements in the same order. See - https://en.wikipedia.org/wiki/Sorting_algorithm#/media/File:Sorting_stability_playing_cards.svg

Additionally, two more subtypes of algorithms exist: in-place and out-of-place or not-in-place. In-place algorithms do not use an auxiliary data structure, whereas not-in-place algorithms do.

The 'Basic' Algorithms

Bubble Sort: loops through an array and checks each number against it's neighbor and moves it up or down respectively. Average and worst case scenario is O(n^2) which means this is a very slow method. Takes up no extra space however.

Insertion Sort: builds a new array one number at a time, putting each number in it's ordered place. Worst case is O(n^2) but the memory it takes up is minimal. Efficient at sorting tables that are already relatively sorted. Best of the worst three algorithms.

Selection Sort: splits the initial numbers into two groups - one that starts empty and the other with all the current numbers. Selection sort then builds the empty array by finding the lowest number, and going up from there. Worst case - O(n^2) comparisons plus O(n) swaps. Works well where auxiliary memory is very limited.

The (more commonly used) 'Advanced' Algorithms

Merge Sort (stable): this is a fast, efficent way to sort numbers - O(nlogn). Merge sort breaks the data down into individual components, and reassembles the list pairs at a time. Each pair is merged with another pair, while being sorted, until the data is reassembled and, thus, sorted.

Quick Sort (unstable): as the name implies, this is potentially the fastest sorting method. Average is O(nlogn). Quick sort first divides the initial array into two parts, large and small elements, then uses a number to pivot from. Each element is continually broken into large and small parts until the array is sorted.

Heap Sort (unstable): an upgraded selection sort. Worst case and average sort time is O(nlogn), which may be desirable. Breaks array into two parts, sorted an unsorted. Then moves the largest item in the unsorted array to the sorted one. A bit confused on the details of this one. Each time it adds a number to the sorted array it also decreases the numbers it has to check in the unsorted array.

making a gif at giphy.com is as easy as sending a video/images and briefly formating it.

.update_all and .update in rails to update an attribute from a table. This does two actions, changes attribute and saves them to the database


Saturday, 12/2/17

tty-prompt allows for a hash of items to be stored where a method is a value for a key. The method will then be run when the key is selected from the prompt. This is a shortcut - let's blog about this


Friday, 12/1/17

The thing between the pipes of an each/map/select loop is called a block parameter

array = [1, 2, 3]
new_array = array.map { |block parameter| block parameter * 2 }

This diagram helped me visualize how a block can be used in a method https://mixandgo.com/assets/blog/ruby_block_flow-3fbb7a8ec5402bbc7930b1a3dcaa47a913ecc98be39ced10381b1624e9c0ae1b.png


Thursday, 11/30/17

Expanding on blocks. A block, most simply put, is a chunk of code between a do and an end. That do/end can also be represented with curly braces { }


Wednesday, 11/29/17

While doing some math in our mini-capstones (generating orders with some quantity of one thing), the program seemed to be most happy when changing all the numbers involved in the math to_f (to float). This is because when sending and receiving web requests and responses, the HTML communicates using strings. Therefore when math is attempted on those strings, problems occur.

Error message: "undefined method 'something' for nil:NilClass"... means that the class you are calling the method on isn't there.

Authorization vs Authentication: Authentication - are you logged in? Authorization - does the logged in user have the capability to do something

Refactoring code means that you're just changing how the code is designed, not how it's used.

Using break exits a loop, using exit stops the program.

Lambda - using blocks '->'. Normally, methods can't be saved inside of hashes, or arrays, etc. (or else they will run when that data structure is called on). However, if you turn the method into a block by using the lambda, the method can be saved in the data structure and be called upon later.

{method: method_name} #=> this will call the method_name when the hash is used
{method: -> do method_name end} #=> this stores the method_name so that it can be called on at a later time

Tuesday, 11/28/17

So Magic the Gathering has an API... that is great. It's diverse, clean, and seemingly easy to use. I look forward to putting it to work: https://magicthegathering.io/


Monday, 11/27/17

We spoke briefly about stateless web today. This is in reference to the relationship between client and server. Basically, when we log into a website, because the website typically operates across multiple 'hive-minded' servers, we can't continue being logged in on the server side. Because of this, our browser keeps track of the user being logged in, and sends back data to the server to indicate that the user is indeed, logged in. This data comes in two forms: cookies and JSON web tokens.

So the information surrounding encrypted passwords... is awesome. In today's age, passwords are not saved into databases. This is because, if the database gets hacked, you wouldn't want the hackers to get the passwords of everyone inside the database. To combat this, passwords are stored via various encryption methods so that hackers have a much more challenging time retrieving the password once the database is hacked. In class, and when using Rails, we will use bcrypt which is an open source encryption method.


Sunday, 11/26/17

With reference to database use, the term 'key' is associated with the ID, while a foreign key is a column in one table with an ID from another table that connects the data in both tables.


Saturday, 11/25/17

JavaScript, in addition to having operators like +=, -=, etc, also has two other useful operators. ++ and --

let x = 3;
x++; #=> x now equals 4

This is useful for looping an index, or something of that nature, where the value only increases or decreases by one.


Friday, 11/24/17

Set a global variable using $variable_name


Thursday, 11/23/17

You can use a call on a method (with a '.') on the next line of the variable it's being used on


Wednesday, 11/22/17

Active record, which resides in Rails, converts Ruby code into SQL queries... then back to Ruby code after the query has been done. This is how rails communicates with a database.

When writing an SQL query, using something like table_name.find_by allows you to find one item in the database. Whereas using table_name.where allows you to find multiple items that fit the description given.

ILIKE vs LIKE in SQL. ILIKE means the query doesn't have to be case sensitive but LIKE is case sensitive.


Tuesday, 11/21/17

Postico is a tool that can help visualize a postgres (or another type) database.

Adding validations to models for your database prevents "bad data" from entering the database in the first place.


Monday, 11/20/17

A shortcut for adding a migration looks like this:

rails g migration Add(Thing)To(TableName) thing:string

Using this, Rails will build the column for you... you still need to db:migrate though. This can also be used to delete a column.

!! Shortcut !! in Sublime, if you don't highlight anything, you can use cmd + 'c' to copy the whole line and cmd + 'x' to cut a whole line


Sunday, 11/19/17

You can call items in an array using negative numbers. The items being called will start from the end of the array, so in reverse. Like:

array = [5, 1, 8]
array[-1] #=> 8
array [-2] #=> 1

To kill a rails server that is running in the background use:

kill -9 $(lsof -i tcp:3000 -t)

You can use a short if condition at the end of a line of code, instead of using if end

if x > 5
  puts "hello"
end

puts "hello" if x > 5

Saturday, 11/18/17

When calling on the params in the controller piece of rails, you're really supposed to use strings, but rails allows symbols.

params[:id]
Should really be
params["id"]

Friday, 11/17/17

I learned what the '.split' command does in Ruby. You can use .split on a string to split the string into array pieces at a desired location(s).

some_string = "This is a string of words."
string_array = some_string.split(" ")
p string_array #=> ["This", "is", "a", "string", "of", "words."]

Thursday, 11/16/17

When deleting data from a postgresql database, the ID that was used on the deleted data set will not be used again...


Wednesday, 11/15/17

In class we focused on using parameters in the routes of our Rails app. Using params allows you to use the same url base and then modify the later parts of a url to show an individual page... This was, and still is, slightly confusing to me. I'll explain my current understanding in a bit more detail.

First, there are two types of ways to structure a param. The first is using queries. Let's say we have a routes file that includes something like:

get "/my_url" => "controller_name#my_method"

Nothing has changed with how the route was structured, however, when entering the url in a web browser, Rails allows us to set params in the url. Like so:

https://localhost:3000/my_url?some_key=some_value

Notice the '?' after the base of the url. Anything after the question mark will be treated as a key/value pair and entered into the pre-determined Rails hash params. This is known as using a query.

Now let's use the second technique, segmented urls. In this case, the routes code will look a little different:

get "/my_url/:some_key" => "controller_name#my_method"

In this case, we set the key of the key/value hash pair in the routes code. Rails identifies this for you when you use a ':' such as in the example above. Notice how the way the url is typed changes when using this method of setting up params.

https://localhost:3000/my_url/some_value

Instead of using a query with a '?', the value entered immediately after the '/my_url' segement will be placed as the partner to ':some_key' in the params hash.

In both cases, the server will show the Parameters as:

"some_key => some_value"

This key/value can be called on in the Controllers page with something like:

variable_name = params[some_key]

Therefore, we can use, a sort of, variable route. The route url will stay the same, however, each user will have an individually tailored url to use.

(any_string).to_i and/or nil.to_i will have a value of '0'.


Tuesday, 11/14/17

We took a look at booleans today in class. Truthy, Falsey and the like were basically gibberish to me before today. Each coding language has its own definition for when something is truthy (like true) or falsey (like false). In Ruby, only false and nil are falsey and everything else is truthy. Here's an example of this strange use of language...

if 5
  puts "like true"
end

Sidenote: the rule of &&, ruby moves forward as long as previous object is truthy, && is a gate

Sidenote: rule of || moves forward if the previous object is falsey (also a 'gate')

In Rails, using namespaces with controllers can provide more specification to your routes and controllers. Without using namespaces, any edits to your codebase can jeopardize the user's current version of the application. By using version one (v1) and then placing future edits under a 'v2' namespace, you can send updated versions as a unit and not risk the user's experience. To generate this 'v1' namespace on startup of application creation, use:

rails generate controller v1/Users

I briefly delved a bit deeper into looking at class and instance methods as they are used in Ruby. I'm still a bit hazy on some of the details, but I'll lay out my understanding thus far.

Class Yo
  def self.zig
    puts "class method"
  end
  
  def zag
    puts "instance method"
  end
end

Yo.zig #=> "class method"
Yo.zag #=> error - undefined method

Yo.new.zig #=> error - undefined method
Yo.new.zag #=> "instance method"

This example, although rather shallow, explains a bit about how each method works. The instance method acts on an instance of the Class Yo, while the class method acts without the instance of Yo. How is this useful? Class methods are useful when not dealing with an individual instance of that class. They can be somewhat separated from the individual. Instance methods, on the other hand, act with that individual instance of the class.

!! Shortcut !! in terminal, to type two different commands on the same line, use '&&'.


Monday, 11/13/17

In building our own API using Rails, we discussed a few different methods used to seed a database after creating it. After setting up the database/routes/controller using Rails, we first started building the data using the terminal. This was done by creating new instances of our created model using '.new' and followed by '.save'. It looked something like this:

contact = Contact.new(first_name: "Name", last_name: "LName")
(output of new contact info here)
contact.save

We repeated this process a couple of times to build a contact list in our database. However, using the seed file that Rails provides is actually a more efficient way to structure the data entry. After building the seed file with a similar list of contact instances shown above we then used the command: rails db:seed to tell Rails to run the 'seed' file.

In addition, using a '.create' method is another useful shortcut. '.create' does the job of '.new' and '.save' with one command. Here's an example: Contact.create(first_name: "Name", last_name: "LName")

We also had a homework assignment that introduced us to a new loop tool: '.map'. The '.map' method is similar to an each loop, however, it is useful for mapping an array of things and turning them into a new array of things + something_new. For example:

new_array = old_array.map{ |i| i * 2 }

In this case, the new array would simply include each value from the old array multiplied by 2. So:

old_array = [2, 5, 9]
(do the mapping)
new_array = [4, 10, 18]

I also briefly read more information about using require vs load

'require' reads and parses files only once, when they were referenced for the first time.

'load' reads and parses files every time you call 'load'.

!! Shortcut !! in terminal when sliding the cursor between letters, hold 'option' instead to slide between words


Sunday, 11/12/17

Today we started using Ruby on Rails. We used a couple commands to get this started, but importantly is the interaction between routes + controllers in rails. We outlined the format for specifying the route within the rails folders. This tells rails where to go next (!controller!) when the user types in a specific URL in their browser. The controller, once formatted with functions or what-have-you, will tell the browser what to show the user (response).

This is a common line of code for the route file from Rails:

'get "/hello_url" => "pages#hello_method"'

In Ruby, to capitalize only the first letter in a string, use the '.capitalize' method

pk = "bulbasaur"
p pk.capitalize
output - "Bulbasaur"

Discovered that there is a Pokémon API at https://pokeapi.co/ this could have very useful implications for the Pokémon terminal app...

!! Shortcut !! - 'cmd + t' in terminal opens another terminal tab

!! Shortcut !! - 'cmd + p' in Sublime will find a file within a folder


Saturday, 11/11/17

In Ruby you can make a piece of text appear on a new line (at least in the terminal) by using '\n' before the text!

Similarly, using 'print' instead of 'puts', when followed with a gets.chomp user input command, allows the user to type on the line where the text is instead of below it. Here are examples of both:

print "Please enter your name: "(user input will go here)
puts "Please enter your name: "
(user input will go here)'
Main menu Hello

will output as it reads

"Main menu \nHello"

will output

Main menu
Hello

Friday, 11/10/17

I began developing a silly Pokemon game app for the terminal today.

In the process I hope to synthesize some of the material I'm learning, as well as figure out new Ruby syntax. One such bit, is the sleep command.

sleep 6
sleep(4.minutes)
sleep(8.hours)

An unspecified unit of time after the sleep command will default to seconds, otherwise a unit of time can be specified as used above.


Thursday, 11/9/17

What is the interwebs? A question that has long plagued society, has finally been answered in class today.

All joking aside, we went over a more formal definition of how the internet... well, works. At its most fundamental level, the internet is a series of web requests and responses between a client device and a server. When you type a url into the search bar of your browser, you are sending a request to the server for information. That server responds with the appropriate information needed to complete the search and your web browser interprets that message in a visually appealing format for the user to then, use. Obviously there is a bit more going on under the hood, but that is the gist of basic internet functionality.

We also spent a significant amount of time in class working, for the first time, with APIs (Application Programming Interface). An API is basically a data bank that can be used by programmers. Various websites provide APIs for use, many of which are free. Using an API providers another important layer of depth to a programmer's repertoire since using an API allows you to work with realtime data. This adds a level of synthesis to programming and we used this knowledge to start working on basic terminal apps in class. This leaves us yet another step closer towards bigger, more intricate projects!

!! Shortcut !! - In Sublime, using 'cmd + ctrl + (arrow up or down)' allows you to move a chunk of code up or down, without breaking the code above or below it. This is an alternative to copy/paste useful for moving pieces of code a couple of lines.


Wednesday, 11/8/17

I was reading a blog post about parameters and arguments used in methods, and found some new syntax. One part, is setting a default argument value. It looks like:

def example_method(a, b="default b")
end

When this method is called, you can either pass in one or two arguments. Passing in one argument to assign a value to 'a' would work, because then the value for 'b' becomes the default value. But if two arguments are passed in, the 'b' value can be changed appropriately

Along a similar line, is the use of the splat operator. Putting an asterisk before your argument variable allows the method to take in any number of arguments and collect them into an array. Here's an example:

def example_method(*args)
p args
end

example_method("hello", "welcome", "goodbye")

returns: ["hello", "welcome", "goodbye"]

This allows the method to be more flexible with its input. However, be careful, because this can create some sticky situations when using the arguments inside the method.

In class we took a look at the use of modules vs classes. In short, a module once set up is simply a collection of methods. These methods can be used when the module is inserted into a class. Such as:

module Hello
  def hi
    puts what's up
  end
end

class Greetings
include Hello
end

In this case, the class 'Greetings' would receive the method 'hi' within the module 'Hello'.

We also went over how Ruby goes about including other files within code.

require "./file_name_here"

Placing this at the beginning of your code will load in that other file (can do multiple times). In this case the './' looks for the other file within the current folder (directory) you are working in.

!! Shortcut !! - To open multiple windows in sublime - 'cmd + option + (number of rows)'


Tuesday, 11/7/17

Quick and awesome keyboard shortcut for the day - 'cmd + return' allows you to go to the next line in the middle of sentence, without pushing the rest of the sentence to the next line. Also, 'cmd + shift + return' lets you do the same thing but in reverse! This pushes your cursor line to the one above the line you were previously in.

In class we also learned the meaning of the acronyms DRY and WET, as they pertain to code.

DRY stands for: Don't Repeat Yourself

WET: Write Everything Twice

In general it is better practice to have DRY code. Don't repeat code you don't have to!

Getting a little more technical - I also learned how to keep OOP (Object Oriented Programming) classes more... dry. Classes can include all the other methods of a previous class by using some fairly simple syntax. This process is known as inheritance. It looks something like this:

class Car < Vehicle
end

In this case, the Car class would inherit all the methods available in the Vehicle class. This is in addition to any new methods written inside the Car class (which would only be available to the Car class).


Monday, 11/6/17

Today I learned... quite a lot.

Ruby has quite a bit of useful shortcuts, specifically relating to the use of classes. Now I can use attr_reader, attr_writter, and att_accessor to have Ruby create reader/writter methods for me. This reduces the amount of redunant code that needs to be written inside the class.

In addition, I learned how to use an 'input-hash' inside the initialize argument of a class. Using a hash for input allows more flexibility when adding information into the class.

In class we also spent time learning how to upload gits to github and thus backing up code onto an online database. Most important to this, was adding the 'git push origin master' to our list of commonly used git terminal commands. This command uploads the git being worked on to github. The frequent steps will go:

  1. git add --all
  2. git commit -m "name"
  3. git push origin master

Sunday, 11/5/17

Today I learned the utility offered by creating a TIL gist in Github.

Sample code can be written using triple backticks

puts "sample"

I also learned how to use git in the terminal to save copies of work. These previous iterations of a file/folder can be used as a baseline of material to continue to build from.

@mdaftab88
Copy link

A great resource. You should keep it growing.

Thanks!

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