Skip to content

Instantly share code, notes, and snippets.

@lucianghinda
lucianghinda / api_response.rb
Created March 30, 2024 18:16
Mastodon Client
module Mastodon
ApiResponse = Data.define(:body, :headers, :code, :links)
end
@lucianghinda
lucianghinda / parser.rb
Created January 8, 2024 09:55
Gemfile parser with Prism
# frozen_string_literal: true
require "prism"
module RubyGems
module GemList
class Parser
def initialize(list, rubygems_client: RubyGems::Client.new)
@list = list
@rubygems_client = rubygems_client
@lucianghinda
lucianghinda / parser.rb
Created December 1, 2023 04:40
Parse Ruby gems
require "prism"
class Parser
def initialize(list, rubygems_client: RubyGems::Client.new)
@list = list
@rubygems_client = rubygems_client
end
def parse
return parse_gemfile_format if gemfile_format?
@lucianghinda
lucianghinda / simple ruby framework.rb
Last active April 30, 2023 08:06
Sample HTTP server in Ruby
require 'socket'
class Handler
def initialize(port)
@server = TCPServer.new(port)
end
def start
loop do
client = @server.accept
@lucianghinda
lucianghinda / custom-types.rb
Created March 26, 2023 07:10
Example of using custom dry types
require 'dry/schema'
require 'dry/types'
class MyObject
def initialize(value)
@value = value
end
def value
return @value if @value.is_a?(Array)
@lucianghinda
lucianghinda / benchmark_ruby_array_bsearch.rb
Created September 7, 2022 06:51
Benchmark Ruby Array#bsearch
# frozen_string_literal: true
require "benchmark"
require "benchmark/ips"
array = Array.new(1000) { Random.rand(100) }.sort
n = 50_000
Benchmark.bmbm do |benchmark|
benchmark.report("bsearch") do
# Code Summary
# 📖 https://paweldabrowski.com/articles/public-private-and-protected-in-ruby
# Part 1/5: Common way of defining private methods
class Person
def name; end
private
def age; end
@lucianghinda
lucianghinda / testing-and-op.rb
Created April 21, 2022 04:35
What does ruby && operator return
# nil and Truthy => nil
x = nil
y = Object.new
puts "when x=#{x.class} and y=#{y.class} then x && y returns #{(x && y).inspect} => x"
x = nil
y = true
puts "when x=#{x.class} and y=#{y.class} then x && y returns #{(x && y).inspect} => x"
# nil and falsy => nil
@lucianghinda
lucianghinda / using-include-vs-extend.rb
Created March 22, 2022 04:03
Example of using include and extend in Ruby
module WithInstanceMethod
def whoami
puts self.inspect
end
end
class One
include WithInstanceMethod
end
@lucianghinda
lucianghinda / .licensed.yml
Created July 26, 2020 20:06
Example of .licensed.yml file to be used with licensed gem
sources:
bundler: true
npm: true
allowed:
- mit
- apache-2.0
- bsd-2-clause
- bsd-3-clause
- isc