Skip to content

Instantly share code, notes, and snippets.

@max-power
Last active November 5, 2017 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max-power/4af74bd05fd26fbe1b2593849cc02894 to your computer and use it in GitHub Desktop.
Save max-power/4af74bd05fd26fbe1b2593849cc02894 to your computer and use it in GitHub Desktop.
Ruby attribute initialiser
class Attributes < Module
def initialize(*attr_names)
@attr_names = attr_names
define_method :attributes { attr_names }
end
private
def included(base)
super
base.send :include, Initializer
base.send :attr_accessor, *@attr_names
end
module Initializer
def initialize(**attrs)
super()
attrs.each { |k,v| send("#{key}=", val) if respond_to? "#{key}=" }
yield self if block_given?
end
end
end
class Book
include Attributes.new(:title, :author, :pages)
end
Book.new(author: "David Foster Wallace", title: "Infinity Jest", pages: 1079)
Book.new(title: "Brave New World") do |b|
b.author = "Aldous Huxley"
b.pages = 288
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment