Skip to content

Instantly share code, notes, and snippets.

# bad
properties.present? && properties[:user].present? && properties[:user][:profile].present?
# Better approach
properties.try(:[], :user).try(:[], :profile).present?
sample_hash = { a: 1, b: 10 }
# bad
sample_hash.merge!({ c: 20, d: 30 })
# good
sample_hash.merge!(c: 20, d: 30)
# bad
params[:search_type].present? && params[:search_type] == 'Dashboard'
# good
params[:search_type] == 'Dashboard'
# best
# Will return value of name or nil
properties.dig(:user, :profile, :name)
# Will return true or false
properties.dig(:user, :profile, :name).present?
# Below is our complete hash example.
properties = { user: { profile: { name: 'Naiya' },
bank: { account: '123' } } }
# This is having nil in profile details.
properties = { user: { profile: nil } }
# This has no user data.
properties = { user: nil }
@NaiyaShah-BTC
NaiyaShah-BTC / nested_hash.rb
Created March 13, 2019 07:30
Different levels of data of hash.
# Below is our complete hash example.
properties = { user: { profile: { name: 'Naiya' }, bank: { account: '123' } } }
# This is having nil in profile details.
properties = { user: { profile: nil } }
# This has no user data
properties = { user: nil }
# May be possible to have no data set to properties
def save_tokens(access, refresh)
TokenCred.create!(access: access, refresh: refresh)
end
def upload_zip_to_box
token_refresh_callback = lambda { |access, refresh, identifier| save_tokens(access, refresh) }
client = Boxr::Client.new(TokenCred.last.access,
refresh_token: TokenCred.last.refresh,
client_id: ENV['CLIENT_ID'],
client_secret: ENV['CLIENT_SECRET'],
def save_tokens(access, refresh)
TokenCred.create!(access: access, refresh: refresh)
end
def client
token_refresh_callback = lambda { |access, refresh, identifier| save_tokens(access, refresh) }
Boxr::Client.new(TokenCred.last.access,
refresh_token: TokenCred.last.refresh,
client_id: ENV['CLIENT_ID'],
client_secret: ENV['CLIENT_SECRET'],
def token_catcher
tokens = Boxr::get_tokens(params['code'],
grant_type: 'authorization_code',
assertion: nil,
scope: nil,
username: nil,
client_id: ENV['CLIENT_ID'],
client_secret: ENV['CLIENT_SECRET'])
TokenCred.create!(access: tokens['access_token'],
refresh: tokens['refresh_token'])
SIZES_ARR = [[167, 200, 'S'], [325, 390, 'M'], [625, 750, 'L']]
SIZES = [%w[small S], %w[medium M], %w[large L], %w[extra_large EL]]
def crop_and_resize
key = self.img.path[1..-1]
S3.bucket('unikaihatsu-s3').object(key).get(response_target: Rails.public_path.join(self.img_file_name))
original_file = Rails.public_path.join(self.img_file_name)
image = Magick::Image.read(Dir.glob(original_file).first)
cropped_img = image[0].crop(150, 0, 1500, 1800).write(Rails.public_path.join("EL_#{self.img_file_name}"))
File.delete(original_file) if File.exist? original_file