Skip to content

Instantly share code, notes, and snippets.

@alexishida
Last active September 5, 2024 14:00
Show Gist options
  • Save alexishida/3b5f79d51f7769ee20afdb9549a25270 to your computer and use it in GitHub Desktop.
Save alexishida/3b5f79d51f7769ee20afdb9549a25270 to your computer and use it in GitHub Desktop.
Comandos Ruby e Rails
# COMANDOS
rails new appname -d postgresql
rails new appname --api
gem install rails -v 6.1.4.4
rails _6.1.4.4_ new myapp
# Rails sem webpack
rails new app-name --skip-webpack-install --skip-javascript
# Removendo o carregamento onhover de links
<meta name="turbo-prefetch" content="false">
# Config git origin repository to existing project
cd existing_folder
git init --initial-branch=main
git remote add origin [email protected]:group/project.git
git add .
git commit -m "Initial commit"
git push -u origin main
# Active storage image processing
# https://github.com/rails/rails/blob/main/guides/source/configuring.md#configuring-active-storage
sudo apt install imagemagick libvips
# Config host
https://guides.rubyonrails.org/configuring.html#configuring-middleware
# Postgres dev packages
sudo apt-get install libpq-dev
# Mariadb dev packages
sudo apt-get install libmariadbd-dev
# Listar Gems instaladas
gem query --local
# Mysql dev packages
sudo apt-get install mysql-server mysql-client libmysqlclient-dev
# Alterando o banco de dados de uma aplicacao
rails db:system:change --to=mysql
# Install Node.js on Ubuntu:
mkdir -p /etc/apt/keyrings
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_20.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list
apt update
apt install -y nodejs
# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_13.x | bash -
apt-get install -y nodejs
# Comando pra copiar os geradores do scaffold
mkdir -p lib/templates/erb/scaffold && \
cp $(bundle show railties)/lib/rails/generators/erb/scaffold/templates/* lib/templates/erb/scaffold
# Models from existing tables
class YourIdealModelName < ActiveRecord::Base
self.table_name = 'actual_table_name'
self.primary_key = 'ID'
self.sequence_name = 'name_seq'
belongs_to :other_ideal_model,
:foreign_key => 'foreign_key_on_other_table'
has_many :some_other_ideal_models,
:foreign_key => 'foreign_key_on_this_table',
:primary_key => 'primary_key_on_other_table'
end
# Trix min-height
trix-editor {
&.form-control {
min-height: 20rem;
height: auto;
}
}
# Disable Trix Attachment
document.addEventListener("trix-file-accept", (e)=>{
e.preventDefault();
});
trix-toolbar .trix-button-group--file-tools {
display: none;
}
# Load
$LOAD_PATH.unshift File.dirname(__FILE__)
# Usando outro banco de dados
rails g active_record:model Animal name:string
rails g scaffold Organization type_of:string{20} name:string{100} email:string{80} cnpj:string{14} since:date site:string photo:string address:references --no-test-framework
rails g scaffold media filename:string url:string resource:references{polymorphic}:index --no-test-framework
rails g controller nome --no-test-framework
rails generate controller home index --no-helper --no-assets --no-controller-specs --no-view-specs
rails g migration add_type_of_to_users type_of:string{20}
rails g migration remove_endereco_from_cliente endereco:string
rails g model New title:string{50} content:text image:string{50} city:references --no-test-framework
rails g model SourceTag tag:references source:references{polymorphic}:index --no-test-framework
rails g scaffold Teste money:decimal{10.2} --no-test-framework
// Para ver todas as tasks rake disponíveis no seu projeto
rake -T
rails generate controller foo bar --skip-template-engine
create_table :source_tags, id: :uuid do |t|
t.references :tag, type: :uuid, index: true, foreign_key: true
t.references :source, type: :uuid, polymorphic: true
t.string "tx_status", limit: 1, default: "Q"
t.string :wallet, limit: 42, null: false, index: { unique: true, name: 'uq_wallets' }
# Executando App em Rails
bundle exec rails runner App.run
bundle exec rails runner app.rb
class App
def self.run
end
end
# Mostra o log no rails exec
ActiveRecord::Base.logger = Logger.new STDOUT
# Verifica o ambiente
Rails.env.production?
# Rails em producao assets /config/environments/production.rb
config.public_file_server.enabled = true
# Add /lib config/application.rb
config.autoload_paths << Rails.root.join('lib')
# Force type Rails
self.attribute('valor', :integer)
# List of Rails Model Types
:binary
:boolean
:date
:datetime
:decimal
:float
:integer
:primary_key
:string
:text
:time
:timestamp
:hstore
:array
:cidr_address
:ip_address
:mac_address
# The Model methods are:
find
create_with
distinct
eager_load
extending
from
group
having
includes (more efficient than join, monitoring sql queries with bullet gem)
joins
left_outer_joins
limit
lock
none
offset
order
preload
readonly
references
reorder
reverse_order
select
where
def change
create_table :table do |t|
t.column # adds an ordinary column. Ex: t.column(:name, :string)
t.index # adds a new index.
t.timestamps
t.change # changes the column definition. Ex: t.change(:name, :string, :limit => 80)
t.change_default # changes the column default value.
t.rename # changes the name of the column.
t.references
t.belongs_to #alias for references
t.string
t.text
t.integer
t.float
t.decimal
t.datetime
t.text
t.timestamp
t.time
t.date
t.binary
t.boolean
t.remove
t.remove_references
t.remove_belongs_to
t.remove_index
t.remove_timestamps
end
end
# Scope examples
scope :created_before, ->(time) { where("created_at < ?", time) }
scope :search, -> term { term ? where('upper(bairros.nome) LIKE upper(?)', "%#{term}%") : nil }
# config
module MyApp
class Application < Rails::Application
# ...
config.foo = ActiveSupport::OrderedOptions.new
config.foo.bar = :bar
end
end
# JQUERY AJAX CSRF
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
# NGINX HTTPS PROXY PASS CSRF
Nginx Headers (X-Forwarded-Ssl on, X-Forwarded-Port 443 and X-Forwarded-Host <your hostname>)
# Carregando seeds da pasta db/seeds
Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].sort.each do |seed|
load seed
end
# Localizando PATH do ruby no rbenv para colocar no RubyMine
$ rbenv which ruby
/usr/local/rbenv/versions/2.6.2/bin/ruby
# Update Bundler 2.0
gem install bundler
gem update --system
# Mongodb Rails
rails new mongo-people --skip-active-record (se quiser)
https://docs.mongodb.com/mongoid/master/tutorials/mongoid-installation/
https://richonrails.com/articles/mongodb-and-rails
# Mongoid type
Array
BigDecimal
Boolean
Date
DateTime
Float
Hash
Integer
BSON::ObjectId
BSON::Binary
Range
Regexp
Set
String
Symbol
Time
TimeWithZone
BigDecimal
Date
DateTime
Range
# instalando nodejs e yarn
curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
apt-get install nodejs -y --no-install-recommends apt-utils
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update && sudo apt-get install yarn -y
# Desabilitando as rotas de mailbox e storage
# For the ActiveStorage routes you'll have this config for your config/application.rb
config.active_storage.draw_routes = false
Comente # require "action_mailbox/engine"
# Ruby Exceptions
begin
do_something()
rescue StandardError => e
# Only your app's exceptions are swallowed. Things like SyntaxErrror are left alone.
end
# These are most of Ruby's built-in exceptions, displayed hierarchically:
Exception
NoMemoryError
ScriptError
LoadError
NotImplementedError
SyntaxError
SignalException
Interrupt
StandardError
ArgumentError
IOError
EOFError
IndexError
LocalJumpError
NameError
NoMethodError
RangeError
FloatDomainError
RegexpError
RuntimeError
SecurityError
SystemCallError
SystemStackError
ThreadError
TypeError
ZeroDivisionError
SystemExit
# Configuração do Number Oracle
# conf/database.yml
nls_numeric_characters: '.,'
# GUIDES
# Hotwire turbo atrributes
https://turbo.hotwired.dev/reference/attributes
Ruby
https://github.com/rubensmabueno/ruby-style-guide/blob/master/README-PT-BR.md
Rails
https://github.com/bbatsov/rails-style-guide
# GEMS
https://github.com/flyerhzm/bullet
# LINKS
https://hackernoon.com/27-gems-i-use-in-almost-every-project-832986551df8
http://guides.rubyonrails.org/
http://guides.rubyonrails.org/association_basics.html
http://guides.rubyonrails.org/generators.html
http://guides.rubyonrails.org/action_controller_overview.html
http://guides.rubyonrails.org/layouts_and_rendering.html
https://www.tutorialspoint.com/ruby-on-rails/rails-controllers.htm
http://guides.rubyonrails.org/active_record_querying.html
http://api.rubyonrails.org/classes/ActiveRecord/Base.html
https://www.railstutorial.org/book
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment