Skip to content

Instantly share code, notes, and snippets.

@madkap
Last active September 9, 2016 19:20
Show Gist options
  • Save madkap/dc0e613f3f555fc79ef9 to your computer and use it in GitHub Desktop.
Save madkap/dc0e613f3f555fc79ef9 to your computer and use it in GitHub Desktop.
GTK - Ruby / Rails / JS /

ActiveRecord

Migrations

unique column flag add_index :table_name, :column_name, :unique => true

iphone: Inspector for Mobile Safari doc

railroady -M | dot -Tsvg > doc/models.svg

annotate - Annotates models in project, really helpful to see columns referenced in each model file.

rubocop - Rubocop

trim local branches that aren't on remote.
git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d
trim remote branches locally

git remote prune origin

heroku pg:killall --app emeraldphog

Node.js

Module

A module encapsulates related/shared code into a single unit of code. Understanding module exports

Export a Module
// exports and module.exports are the same object
var exports = module.exports = {};

// create methods for module export
module.exports = {
  sayHelloInEnglish: function() {
    return "HELLO";
  },
       
  sayHelloInSpanish: function() {
    return "Hola";
  }
};

The keyword require is used in Node.js to import modules.

// main.js
var greetings = require("./greetings.js");

// "Hello"
greetings.sayHelloInEnglish();
        
// "Hola"  
greetings.sayHelloInSpanish();

String Functions

Replace

Replace line breaks with <br> tags - Stack Overflow

string.replace(/(?:\r\n|\r|\n)/g, '<br />')

Timeout

  setTimeout ->
    $(e.trigger).text 'Copy command'
  , 3000

Understanding functions

Function literal executed immediately. Stackoverflow

(function($) {
  ...
})(jQuery);

Find keys

Loops through objects within an array and find a key

var lookup = [];
for (var i = 0, len = this.props.pages.portfolio.companies.length; i < len; i++) {
  lookup.push(this.props.pages.portfolio.companies[i].filename)
}
var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
    lookup[array[i].id] = array[i];
}

Do it with filter method

    var result = portfolio.companies.filter(function( obj ) {
      return obj.filename === company;
    })
    return result.length > 0 ? true : false

CAPYBARA DOCUMENTATION: (W/ RSPEC) capybara readme capybara readme

Set an instance variable: controller.instance_variable_set(:@current_user, user)

puts page.html

page.save_screenshot 'filename.png'

save_and_open_page

using_wait_time(10) do
  page.find("tr.entry-done[data-id='#{entries[1].id}'] td.in-workflow")
end

Create a second delay between the creation of each model to have a different created_at time

@jobrun3 = create(:job_run)
sleep(1.second)
@jobrun2 = create(:job_run)
sleep(1.second)

Due to ActiveRecord you can't affect updated_at or created_at at the time of creation in FactoryGirl. ######FactoryGirl Git Issue "In ActiveRecord, you can't set the created_at or updated_at timestamps through the use of #save. At best, you can update the created_at timestamp by using #update_attribute in a second command after the object has been created, but you can't get away with even that for updated_at -- you have to execute SQL."

Ruby / Rails

Models

Variables

@@foo vs @foo - Class and Instance Variables

Validations

validates_presence_of :category - When there is an association and the DB has the category_id validating against the model category checks against the model itself rather than the value given. A much better way to handle it. Stack Overflow

attr_accessor - Creates a variable that isn't persisted in the DB
attr_accessor :foo

# creates:
def foo
 @foo
end
def foo=(str)
 @foo = str
end

Registration.where(created_at: @start..@end) Range of dates

persisted? - it's already in the database

after_initialize :defaults, unless: :persisted?

Associations

belongs_to :approver, class_name: 'User', primary_key: :username, foreign_key: :blessed_by

has_many :deploy_runs
has_many :silos, through: :deploy_runs

Strings

Capitalize first letter of every word
puts 'one TWO three foUR'.split.map(&:capitalize)*' '
#=> One Two Three Four
split()

Convert string to array "one,two,three,four".split(',')

join()

Convert array into string ['one','two','three'].join(', ')

rjust()

If integer is greater than the length of str, returns a new String of length integer with str right justified and padded with padstr; otherwise, returns str. APIdock

"hello".rjust(4)            #=> "hello"
"hello".rjust(20)           #=> "               hello"
"hello".rjust(20, '1234')   #=> "123412341234123hello"
=~

Matches a string to regex StackOverflow

.end_with?, .start_with?, .include?

String methods that returns true/false

JobScheduler::Workers.constants.map(&:to_s)
  .select {|w| w.end_with? "Worker" }
  .reject {|w| %w{Daily Hourly Weekly HighPriority Worker}.any? {|t| w.start_with? t} }  # don't list generic classes
  .reject {|w| w.include? "Java" }  # don't list generic classes
  .map {|w| w.gsub(/Worker$/, "").underscore }
  .sort

Date / Time

Date.new(2014, 08, 09)

To get last day of month do a -1 value Date.new(2015,12,-1) will return Dec 31st

Date.parse('12/01/2015') or '2015-12-30'.to_date - parse from a string or turn a string into a date

strftime strftime documentation

distance_of_time_in_words distance_of_time_in_words - Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds.

Arrays / JSON / Hash

Array solutions

removing duplicates from two arrays. Notice difference between length of arrays and who substracts from whom.

a1 = ['a','b','c']
b1 = ['a','b','c','d']

(a1 - b1)
=> []
(b1 - a1)
=> ['d']
%w() %W() Array of Strings

%w(), %W()Create an array of strings with %w(), to interpolate values use %W()

%w(hello there person)
# ['hello', 'there', 'person']

foo = 'hello'
%W(#{foo} there person)
# ['hello', 'there', 'person']
* - splat operator.

It expands an Array into a list of arguments. It expands any object that responds to to_ary/to_a, or to_a Splat for beginners

keys_to_ignore = ['signature', 'silo_id', 'status_id', 'job_run_name_id']
JSON.parse(self.to_json).except(*keys_to_ignore).tap do |hash|
keys_to_ignore - remove keys from a hash

keys_to_ignore = ['ignore1', 'ignore2'] JSON.parse(self.to_json).except(*keys_to_ignore)

Enumerables

Iterates over a collection, passing the current element and the memo to the block. memo should be something that can be modified, not numbers or true/false

each_with_object(memo)
STATUSES = Status.all.to_a.each_with_object({}){ |status, hash| hash[status.name] = status.id }

Combine all elements of enum and has a accumulator value(memo) that you add to.

@order.order_items.inject(0){|t, oi| t + 1 if oi.ordered_item}

method returns true if matches anything in the collection

variants.any?(&:in_stock?)
%w{ant bear cat}.any? {|word| word.length >= 3}

Misc

p vs. puts

p does an inspect instead of a .to_s like puts does

method(options = {}, html_options = {}) - when method accepts a hash for multiple options
grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {}) 

grouped_collection_select :ordered_item_id, Shoppe::ProductCategory.all, :variants, :name, :id, :parent_name, {prompt: 'Select Product'}, {class: 'select2'}
defined?()

Find out if an Object has been defined defined?(Rails) && Rails.env == 'production'

tap()

Tap an object and have a block that allows you to work on stuff and return itself.

.try(*a, &b)

If you know an object may be NIL you can see if it's there before calling the method. Takes in two arguments, first is the method, 2nd are the parameters into the method. (try documentation)[http://apidock.com/rails/Object/try]

lsof -i :3000 - List of files open. Specifically on a port

ps aux | grep redis - list process status. aux list status currently running

kill $(ps aux | grep -E 'ruby|redis|postgres|sidekiq' | grep -v grep | awk '{print $2}')

sudo du -sh /.DocumentRevisions-V100 - how big a folder is

ln -s /path/to/original /path/to/symlink - link

screen -r, screen -S, screen -ls, ctrl + a, d, screen -X -S [session] quit- man screen

sudo su - wday - sudo to change as user

find PATH_TO_START_SEARCH_FROM -type d | grep DIRNAME - find a directory

alias showhidden="defaults write com.apple.finder AppleShowAllFiles TRUE"
alias hidehidden="defaults write com.apple.finder AppleShowAllFiles FALSE"
growl() { echo -e $'\e]9;'${1}'\007' ; return ; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment