Skip to content

Instantly share code, notes, and snippets.

@flynn1982
flynn1982 / autovivifying_ruby.rb
Created May 20, 2020 20:31
Ruby Autovivifying (Nested Hashes without having to declare the hashes in the tree first)
def autovivifying_hash
Hash.new {|ht,k| ht[k] = autovivifying_hash}
end
hash = autovivifying_hash
hash['a']['b']['c']['d']['e'] = 'hello'
puts hash['c']
puts hash['a']
puts hash['b']
@flynn1982
flynn1982 / validate_uri.rb
Created September 5, 2019 20:02
validate url or uri
def uri?(string)
uri = URI.parse(string)
%w( http https ).include?(uri.scheme)
rescue URI::BadURIError
false
rescue URI::InvalidURIError
false
end
See https://stackoverflow.com/questions/5331014/check-if-given-string-is-an-url
@flynn1982
flynn1982 / model.rb
Created August 20, 2019 21:10
Conditional scope example in rails
Some Model Name
...
# scopes
scope :by_category, ->(category) { where(category: category) if category.present? }
scope :by_project_id, ->(id) { where(project_id: id ) }
...
# class methods
@flynn1982
flynn1982 / cool_file_generator.rb
Created July 11, 2019 23:56
Rails Custom Generator and Thor Example
class CoolFileGenerator < Rails::Generators::Base
def set_file_name
@file_name = "cool_file.rb"
end
def create_cool_file
body = ask "What should I write into the file?"
create_file @file_name, "Insert after me \n" + body
end