Skip to content

Instantly share code, notes, and snippets.

@nsmmrs
nsmmrs / main.dart
Created February 12, 2025 04:29
Dart null safety
void main() {
final List<List<int>> grid = [
[1,2,3],
[4,5,6],
];
// I thought this would fail to compile
// since grid[2] could be null:
print(grid[2][3]);
@nsmmrs
nsmmrs / lazy_demo.rb
Created August 4, 2023 15:44
Ruby Lazy Enumerator Demo
def lazy_demo(n, group_size:n, groups:n)
(1..Float::INFINITY)
.lazy
.map{|x| x * n }
.select{|product| product.even? }
.each_slice(group_size)
.map{|group| group.map(&:to_s).join(",") }
.first(groups)
end
@nsmmrs
nsmmrs / random_record.rb
Last active December 5, 2024 15:04
Rails Model "random_record" Helper
class ApplicationRecord
def self.random
max = maximum(primary_key)
return if max.nil?
find_random = lambda do
order(primary_key).find_by(primary_key => (rand(max)..))
end
@nsmmrs
nsmmrs / error_helpers.rb
Created April 22, 2023 20:45
Rails Validation Error Helpers
class ApplicationRecord
def add_error(attribute, type, message=nil)
attribute = attribute.to_s.to_sym
type = type.to_s.to_sym
errors.add attribute, type, message: message
end
def has_error?(attribute, type)
@nsmmrs
nsmmrs / string_enum.rb
Created April 22, 2023 20:28
Rails "string_enum" Helper
class ApplicationRecord
def self.string_enum(column_name, values, **options)
enum column_name => values.map(&:to_s).index_by(&:itself), **options
end
end
@nsmmrs
nsmmrs / hash_deep_slice.rb
Created April 22, 2023 04:25
Hash#deep_slice
class Hash
def deep_slice(schema)
self.class.deep_slice(self, schema)
end
def self.deep_slice(hash, schema)
nested_schemas = schema.last.is_a?(Hash) ? schema.last : {}
keys = schema.reject{|e| e.is_a?(Hash) } + nested_schemas.keys
@nsmmrs
nsmmrs / hash_shape.rb
Created April 22, 2023 04:24
Hash#shape
class Hash
def shape
self.class.shape_of self
end
def self.shape_of(hash)
hash.sort_by{|k,v| k.to_s }.map do |k,v|
v = case v
when Array
@nsmmrs
nsmmrs / hash_breadcrumbs.rb
Last active April 22, 2023 04:23
Hash#breadcrumbs
class Hash
def self.breadcrumbs(hash)
hash.flat_map do |k,v|
if v.is_a?(Hash)
breadcrumbs(v).map{|p| [k, *p]}
else
[k]
end
end
@nsmmrs
nsmmrs / shell_command.rb
Last active September 3, 2022 13:42
A convenience wrapper around `Open3.capture3` for easily running commands, capturing the output, and handling failures.
require "open3"
require "json"
class ShellCommand
attr_reader :line, :stdin, :binmode, :stdout, :stderr, :status
def initialize(line, stdin, binmode, stdout, stderr, status)
@line = line
@stdin = stdin
module ValueObject
def ==(other)
case other
when ValueObject
self.object_value == other.object_value
else
false
end
end