Skip to content

Instantly share code, notes, and snippets.

View thiagoa's full-sized avatar

Thiago Araújo Silva thiagoa

  • thoughtbot
  • Natal / RN - Brazil
View GitHub Profile
# This works for the use case below, but not for every timeout-related task.
defmodule Timeout do
@default_timeout 1_000
@count 0
def wait(cond, on_after, timeout \\ @default_timeout) do
result = call time(), @count, timeout, cond, cond.()
on_after.(result)
end
defmodule Hub do
defmacro on_match(pattern, do: on_match, after: on_after) do
on_match = quote do
term -> Hub.match term, unquote(pattern), do: unquote(on_match)
end
quote do
receive(do: unquote(on_match), after: unquote(on_after))
end
end
defmodule Hub do
use GenServer
def start_link(options \\ []) do
GenServer.start_link(__MODULE__, :ok, options)
end
def init(:ok) do
{:ok, []}
end
defmodule TermEvaluator do
def call(term, pattern: pattern) do
term = Macro.escape(term)
ast = quote do
case unquote(term) do
unquote(pattern) -> true
_ -> false
end
end
require 'benchmark/ips'
require 'active_support/core_ext/hash'
def sample
{ a: 1, b: 2, c: 3, d: 4, c: 5, d: 6, e: 7, f: 8, g: 9, h: 10 }
end
Benchmark.ips do |x|
x.report 'map + to_h' do
h = sample
module Imageable
def self.included(model_class)
model_class.has_many :images, polymorphic: true
model_class.extend ClassMethods
end
module ClassMethods
def has_one_image(*names)
names.each do |image_kind|
define_method image_kind do
module Imageable
def self.build(methods)
mod = Module.new do
methods.each do |method|
define_method method do
images.find { |image| image.kind == 'main_image' }
end
end
end
class ModuleFactory < Module
def initialize
define_a_method
end
private
def define_a_method
module_eval do
def my_method
class Imageable < Module
def initialize(has_one: %i(main_image))
has_one.each { |image_kind| define_image_getter(image_kind) }
end
private
def included(model_class)
model_class.has_many :images
end
class Project
include Imageable.new(has_one: %i(main_image secondary_image))
end
project = Project.new
project.main_image #=> <Image kind="main_image" imageable_type="Project">
project.secondary_image #=> <Image kind="secondary_image" imageable_type="Project">