Last active
November 5, 2017 22:13
-
-
Save max-power/4af74bd05fd26fbe1b2593849cc02894 to your computer and use it in GitHub Desktop.
Ruby attribute initialiser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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