Skip to content

Instantly share code, notes, and snippets.

View wyodeb's full-sized avatar
🏠
Working from home

Sergiu Beșliu wyodeb

🏠
Working from home
View GitHub Profile
class Magician
def method_missing(name, *args)
puts "You tried to call #{name} with these arguments: #{args.join(', ')}"
end
end
magician = Magician.new
magician.cast_spell("fireball", "enemy") # You tried to call cast_spell with these arguments: fireball, enemy
class MyClass
def self.create_methods(methods)
methods.each do |method_name|
define_method(method_name) do
"This is method #{method_name}"
end
end
end
create_methods([:method1, :method2])
class DynamicProxy
def initialize(subject)
@subject = subject
end
def method_missing(method_name, *args, &block)
if @subject.respond_to?(method_name)
@subject.send(method_name, *args, &block)
else
super
class FakeNumber
def initialize(value)
@value = value
end
def +(other)
@value + other.to_i
end
def to_i
module Enumerable
def my_map
result = []
each { |item| result << yield(item) }
result
end
end
sum = lambda {|a, b| a + b }
puts sum.call(2, 3) #=> 5
# Example 1: Monkey patching the String class
class String
def to_b
return true if self == "true"
return false if self == "false"
raise ArgumentError.new("invalid value for Boolean: #{self}")
end
end
# Usage:
class UsersController < ApplicationController
def index
@users = UserFilterService.new(params[:query]).filter
end
end
@wyodeb
wyodeb / .rbocop.yml
Last active February 15, 2023 11:29
require: rubocop-rails # If you have rubocop-rails installed
AllCops:
TargetRubyVersion: 3.2.0 # Do not forget to put your Ruby version here
Exclude:
- 'db/**/*'
- 'bin/*'
- 'config/**/*'
- 'lib/**/*'
- 'spec/**/*'
- 'Gemfile'
Proc.new {|string_to_reverse| string_to_reverse.chars.inject([]){|r,c| r.unshift c}.join}.call("string")