Arguments for Included Modules in Ruby

module Slug
def to_param
name.downcase.gsub /\W+/, '-'
end
end
module Slug
def to_param
slug_field.downcase.gsub /\W+/, '-'
end
private def slug_field
name
end
end
class BlogPost < ApplicationRecord
include Slug
private def slug_field
title
end
end
class BlogPost < ApplicationRecord
include Slug, field: :title
end
class BlogPost < ApplicationRecord
include Slug.new field: title
end
class Slug < Module
def initialize field: :name
super() do
define_method :to_param do
public_send(field).downcase.gsub /\W+/, '-'
end
end
end
end
module Foo
end
Foo = Module.new
def foo
bar = Module.new
end
module Foo
def bar
puts 'baz'
end
end
Foo = Module.new do
def bar
puts 'baz'
end
end
Foo = Module.new do
define_method :bar do
puts 'baz'
end
end
class ModuleWithBar < Module
def initialize
super do
def bar
puts 'baz'
end
end
end
end
Foo = ModuleWithBar.new
class ModuleWithArgs < Module
def initialize arg='default'
super()
end
end
class ModuleWithArgs < Module
def initialize arg='default'
super() do
define_method :bar do
puts arg
end
end
end
end
class Foo
include ModuleWithArgs.new
end
Foo.new.bar # prints 'default'
class Cat
include ModuleWithArgs.new 'hello'
end
Cat.new.bar # prints 'hello'
class Slug < Module
def initialize field: :name
super() do
define_method :to_param do
public_send(field).downcase.gsub /\W+/, '-'
end
end
end
end

--

--

Software Developer. Primary love is Rails.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store