Created
August 9, 2013 16:59
-
-
Save jtomschroeder/6195229 to your computer and use it in GitHub Desktop.
custom attrs
This file contains hidden or 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
module Attrs | |
def attr_initialize(*vars) | |
define_method(:initialize) do |*values| | |
unless values.length == vars.length | |
raise ArgumentError, "wrong number of arguments (#{values.length} for #{vars.length})" | |
end | |
vars.zip(values).each do |var, value| | |
instance_variable_set("@#{var}", value) | |
end | |
end | |
end | |
def attr_prop_initialize(*vars) | |
attr_initialize *vars | |
attr_accessor *vars | |
end | |
end | |
class Class | |
include Attrs | |
end |
This file contains hidden or 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
require_relative "attrs" | |
class Test | |
attr_prop_initialize :t1, :t2 | |
def add | |
@t1 + @t2 | |
end | |
end | |
t = Test.new(1, 2) | |
puts t.t1 | |
puts t.add |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment