Skip to content

Instantly share code, notes, and snippets.

View timm-oh's full-sized avatar
🐰

Tim McCarthy timm-oh

🐰
View GitHub Profile
@timm-oh
timm-oh / hash_helper.rb
Created December 26, 2020 17:07
Helper method to convert from dot notation to hash
def dot_to_hash(value)
return value unless value.is_a?(Hash)
value.deep_stringify_keys.each_with_object({}) do |(k,v), result|
root, child = k.split('.')
if child
result[root] ||= {}
result[root][child] = dot_to_hash(v)
else
result[root] = dot_to_hash(v)
end
@timm-oh
timm-oh / readme.md
Created September 27, 2020 10:05
Rails - Remove field_with_error

By default Rails wraps form errors in a div with the class field_with_errors.

There are 2 ways to disable this.

First way is in the application.rb environment file (doesn't make sense just to disable it on a specific environment?):

# config/application.rb

module ApplicationName
@timm-oh
timm-oh / readme.md
Last active September 27, 2020 10:06
Simple time zone support

Basic Usage

This is a super easy way to ensure that timestamps/datetimes etc render correctly according to the timezone that the object is in. In our usage we have a time_zone attribute on our models that stores the time zone in a format that we can find with active support. Example American Samoa, for more examples run bundle exec rake time:zones:all in your rails project.

We weren't aiming to display the datetime in a format relative to the user, but rather just display that the time was in X time zone

# lets assume we have an attribute called start_time
@timm-oh
timm-oh / application_record.rb
Last active May 19, 2024 11:08
Rails 5.2.3: Monkey patch update_all and update_columns to always include updated_at
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
# Didn't change #update_column because it uses #update_columns under the hood.
def update_columns(attrs)
new_attrs = attrs.symbolize_keys
new_attrs[:updated_at] ||= Time.current if self.class.column_names.include?('updated_at')
super(new_attrs)
end
@timm-oh
timm-oh / application_helper.rb
Last active December 17, 2023 21:04
Rails 5.2.3: Cache Active Storage Blobs and Variants through Cloudfront
# app/helpers/application_helper.rb
module ApplicationHelper
# active_storage_item could be a blob or variant object
def proxy_url(active_storage_item, options = {})
options.merge!(host: ENV['ASSETS_HOST']) if ENV['ASSETS_HOST'].present?
# proxy: 'true' allows you to stil have the original functionality while
# being able to proxy through a CDN. You've got to ensure that your CDN
# forwards this param otherwise active storage will always do the default
# behavior which is a redirect to the service.