Skip to content

Instantly share code, notes, and snippets.

@borisrorsvort
Forked from dhh/gist:981520
Last active June 17, 2022 10:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borisrorsvort/b22830b54d22686a4873dd22ac6d5f5d to your computer and use it in GitHub Desktop.
Save borisrorsvort/b22830b54d22686a4873dd22ac6d5f5d to your computer and use it in GitHub Desktop.
Ruby snippets
# Bulk API design
#
# resources :posts
class PostsController < ActiveController::Base
# GET /posts/1,4,50,90
# post_url([ @post, @post ])
def show_many
@posts = Post.find(params[:ids])
end
# PUT /posts/1,4,50,90
def update_many
@posts = Post.find(params[:ids])
Post.transaction do
@posts.each do |post|
post.update_attributes!(params[:posts][post.id])
end
end
end
# POST /posts/many
def create_many
end
# DELETE /posts/1,4,50,90
def destroy_many
end
end
module ClassNamesHelper
def class_names(*args)
classes = []
args.each do |arg|
next unless arg
classes << classes_factory(arg)
end
classes.join(" ")
end
private
def classes_factory(arg)
if arg.is_a?(String || Numeric)
arg
elsif arg.is_a? Array
arg.map { |a| class_names(a) }
elsif arg.is_a? Hash
arg.each_key.select { |key| arg[key].present? }
end
end
end
# spec/support/inline_active_job.rb
# Source: https://gitanswer.com/rails-rails-6-inconsistently-overrides-activejob-queue-adapter-setting-with-testadapter-ruby-496901128#553927324
# useful when testing Turbo with ActiveJob and rspec capybara
RSpec.configure do |config|
config.around(:each, type: :request) do |example|
original_queue_adapter = ActiveJob::Base.queue_adapter
descendants = ActiveJob::Base.descendants + [ActiveJob::Base]
ActiveJob::Base.queue_adapter = :inline
descendants.each(&:disable_test_adapter)
example.run
descendants.each { |a| a.enable_test_adapter(ActiveJob::QueueAdapters::TestAdapter.new) }
ActiveJob::Base.queue_adapter = original_queue_adapter
end
end
require 'net/http'
require 'json'
require 'uri'
class Prerender
ENDPOINTS = "https://api.prerender.io".freeze
def initialize(url, prerender_token)
@url = url
@prerender_token = prerender_token
end
def recache
post_params = {
url: url,
prerenderToken: prerender_token
}
res = Net::HTTP.post(
URI("#{ENDPOINTS}/recache"),
post_params.to_json,
'Content-Type' => 'application/json'
)
if res.code == '200'
puts "Successfully recache URL #{url}"
else
puts res.body
end
end
private
attr_reader :url, :prerender_token
end
class Spinner
def initialize printer=nil
@spinner = %w[| / - \\]
@count = 0
@printer ||= $stderr
end
def print
@printer.print "\r"+@spinner[@count]
@count += 1
@count = 0 if @count > @spinner.size - 1
end
def self.print
@spinner ||= new
@spinner.print
end
end
# 50.times{ Spinner.print; sleep 0.1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment