Skip to content

Instantly share code, notes, and snippets.

@jmscarnatto
Last active February 1, 2024 17:44
Show Gist options
  • Save jmscarnatto/a49bfa23e86cb8e971665ddd79d97ae9 to your computer and use it in GitHub Desktop.
Save jmscarnatto/a49bfa23e86cb8e971665ddd79d97ae9 to your computer and use it in GitHub Desktop.
ruby_snippets.md

Debug

puts caller(0,10); binding.pry

monitor certain field on model

class YourModel < ActiveRecord::Base
  def myfield=(*args)
    puts ">>>>>>>>>>>>>>>>>> #{args}"
    Rails.logger.debug "myfield called at #{Kernel.caller(0,100)}"
    super(*args)
  end
end

💡 Tips

  1. find Model.new or Model.create
  2. remember delagated methods

Tiny assert

def assert
  define_method :equal do |expected|
    return puts "\e[1;32mTest passed!\e[m" if yield == expected  
    puts "\e[1;31mTest failed -- got: #{yield} // expected: #{expected}\e[m" 
  end    
end 

use

assert{ method_to_test }.equal something

Tiny tiny assert

p testing_function == expected

or

puts method_to_tested(param) == whatever ? "\e[32mPassed\e[m" : "\e[31mFailed\e[m"

Run ruby from Rails Console

$ rails c
irb > load "#{Rails.root}/<wherever>/script_to_run_in_rails.rb"

BONUS MySql

Search a column name thorugh all tables in a database

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME LIKE '%column_name%'
        AND TABLE_SCHEMA='database_name';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment