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
class Imageable < Module
def initialize(has_one: %i(main_image))
has_one.each do |image_kind|
define_method image_kind do
images.find { |image| image.kind == 'main_image' }
end
end
end
def included(model_class)
class ModuleGenerator < Module
def build_methods(methods)
module_eval do
methods.each do |method|
define_method(method) do
puts "#{method} was defined in the instance methods"
end
end
end
end
module OneTwoThree
def one
puts 'one was defined as an instance method'
end
def two
puts 'two was defined as an instance method'
end
def three
OneTwoThree = Module.new do
def one
puts 'one was defined as an instance method'
end
def two
puts 'two was defined as an instance method'
end
def three
class DynamicModuleGenerator < Module
def initialize(methods)
module_eval do
methods.each do |method|
define_method(method) do
puts "#{method} was defined as an instance method"
end
end
end
end
class Module < Object
def module_eval
# Only the language has the magic to make this work...
end
# Imagine there are a bunch of other instance methods here.
# Module.new generates objects that respond to these methods.
end
UselessAble.module_eval do
# This is written in the module's instance methods collection
def guess_what?
puts "I'm useless!"
end
end
def UselessAble.who?
puts 'I am an abstract behavior, but I do exist somehow!'
end
asshole_1 = AssHole.new
asshole_1.guess_what? #=> outputs "I'm useless!"
asshole_1.soul #=> outputs "I have no soul!"
asshole_2 = AssHole.new
asshole_2.guess_what? #=> outputs "I'm useless!"
asshole_2.soul #=> outputs "I have no soul!"
module UselessAble
def guess_what?
puts "I'm useless!"
end
end
# Instances of AssHole now respond to "guess_what?" and "soul"
class AssHole
include UselessAble
# Instances of Project respond to every method of Imageable!
class Project
include Imageable
end
# Provides the same collection of methods as Imageable
module SuperImageable
include Imageable
end